【问题标题】:How do you make codes/lookup tables in Elixir? [closed]你如何在 Elixir 中制作代码/查找表? [关闭]
【发布时间】:2011-03-29 15:47:11
【问题描述】:

我正在寻找一种/最好的方法来制作查找表或使用由 Python 的 Elixir 制成的关系数据库中的代码。我什至不确定我在这里的术语是否正确。

例如,我有一个包含 Region 列的 Location 表。我希望 Region 列的值只有“北美”、“中美洲”、“南美洲”、“亚洲/太平洋岛屿”等几个值。值列表将来可能会发生变化。

如何用 Elixir 做到这一点?使用 Enum 似乎是个坏主意,因为这些值是长文本字符串。似乎某种代码会更好(如 1=北美、2=南美等)。如何在数据库中存储和引用这些代码?

【问题讨论】:

    标签: python database activerecord sqlalchemy python-elixir


    【解决方案1】:

    一个建议是规范化您的数据,即在您的 Location 表中,Region 列是一个整数值,代表您的一个区域。然后创建一个 Regions 表,其中仅列出一次您的区域名称。因此 Location 表只引用了 Regions 表的索引(或外键)。

    例如:您的 Regions 表是这样的:

    • id=1, regionname=北美
    • id=2, regionname=南美洲
    • 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 程序员。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-18
      • 1970-01-01
      相关资源
      最近更新 更多