0

ルックアップ テーブルを作成したり、Python の Elixir から作成されたリレーショナル データベースでコードを使用したりするための最良の方法を探しています。ここでの私の用語が正しいかどうかさえわかりません。

たとえば、Region 列を持つ Location テーブルがあります。Region 列の値には、「北アメリカ」、「中米」、「南アメリカ」、「アジア/太平洋諸島」、およびその他の値のみが含まれるようにします。値のリストは将来変更される可能性があります。

Elixirでこれを行うにはどうすればよいですか? 値が長いテキスト文字列であるため、列挙型を使用するのは悪い考えのように思えます。ある種のコードの方が優れているようです (1 = 北アメリカ、2 = 南アメリカなど)。これらのコードをデータベースに保存して参照するにはどうすればよいですか?

4

1 に答える 1

1

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 プログラマーではありません。

于 2011-03-30T14:34:29.463 に答える