1 つの提案は、データを正規化することです。つまり、Location テーブルでは、Region 列は整数値であり、Region の 1 つを表します。次に、地域名を 1 回だけリストする Regions テーブルを作成します。したがって、Location テーブルは、Regions テーブルへのインデックス (または外部キー) を参照するだけです。
例: Regions テーブルは次のようなものです。
- id=1、地域名=北米
- id=2、地域名=南アメリカ
- id=3, regionname=中央アメリカ
- id=4, regionname=アジア/太平洋諸島
次に、 Locations テーブルはこれにインデックスを付けるだけです:
- ID=1、地域=1
- ID=2、地域=2
- ID=3、地域=3
- ID=4、地域=4
- ID=5、地域=2
- ID=6、地域=1
以下は、大雑把ではあるが単純な例です。
from elixir import *
metadata.bind = "sqlite:///"
class Regions(Entity):
regionname = Field(String(255))
class Location(Entity):
region = ManyToOne('Regions')
setup_all()
create_all()
#Create the region names:
na_temp = Regions(regionname="North America")
sa_temp = Regions(regionname="South America")
ca_temp = Regions(regionname="Central America")
ap_temp = Regions(regionname="Asia/Pacific Islands")
session.commit()
#Create links to each region in the location table:
northamerica = Location(region=na_temp)
southamerica = Location(region=sa_temp)
centamerica = Location(region=ca_temp)
asiapacific = Location(region=ap_temp)
anotherarea = Location(region=sa_temp)
yetanotherarea = Location(region=na_temp)
session.commit()
#Get all items from the Location table:
locations = Location.query.all()
#Display the contents of the Location table, and lookup the name from the Regions table
for place in locations:
print "Location table id: {}".format(place.region_id)
print "Lookup region name: {}".format(Regions.get_by(id=place.region_id).regionname)
print
これを行う方法は他にもあります。これは私のアプローチです。私はあなたが出会う最強の Python プログラマーではありません。