我正在寻找一种/最好的方法来制作查找表或在Python的Elixir制作的关系数据库中使用代码。我甚至不确定我的术语是否正确。
例如,我有一个具有Region列的Location表。我希望Region列的值只有“北美”,“中美洲”,“南美洲”,“亚洲/太平洋岛屿”等值。值列表将来可能会发生变化。
如何用Elixir完成这项工作?使用Enum似乎是一个坏主意,因为值是长文本字符串。似乎某种代码会更好(例如1 =北美,2 =南美等)。如何在数据库中存储和引用这些代码?
答案 0 :(得分:1)
一个建议是规范化您的数据,即在您的位置表中,Region列是一个Integer值,代表您的某个Region。然后创建一个Regions表,仅列出您的区域名称一次。因此,Location表只引用Regions表的索引(或外键)。
例如:您的Regions表是这样的:
然后,您的Locations表只对其进行索引:
这是一个简单的,如果粗略的例子:
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程序员。