初心者の質問。宣言型スタイルを使用したパイロン1+SQLA。Pythonは初めてです。
Entityという「マスター」クラスがあります。これらの「子」クラスが有効であるためには、このクラスに属している必要があります。マスタークラスへのリンクは子オブジェクトレベルにあります。私の問題は、子オブジェクトを作成してマスターオブジェクトを作成する方法と、オブジェクト間のリンクを作成する方法を理解できないように見えることです。リンクにはリレーションを利用しています。
したがって、次のように1つのリンクに小野を作成したいと思います。エンティティ1-クライアント1エンティティ2-クライアント2エンティティ3-プロデューサー1エンティティ4-プロデューサー2など。
コードはよりよく説明するかもしれません。
class Entity(Base):
__tablename__ = "entities"
# Primary Key
entity_id = Column(Integer, primary_key=True)
# Data Fields
name = Column(Unicode(255), nullable=False)
def __init__(self, name, description):
self.name = name
def __unicode__(self):
return self.name
__str__ = __unicode__
class Client(Base):
__tablename__ = "clients"
client_id = Column(Integer, primary_key=True)
# Data fields
name = Column(UnicodeText(255), nullable=False, unique=True)
# Entity Link
entity_id = Column(Integer, ForeignKey('entities.entity_id'))
# Mapper
entity = relation('Entity')
def __init__(self, name):
self.name = name
def __unicode__(self):
return self.name
__str__ = __unicode__
コントローラーで、新しいクライアントを作成してエンティティを追加しようとしましたが、失敗しました。以下にコーディングしてください。
client_entity = model.Entity(name=client_name, description=client_name + " added")
client = model.Client(name=client_name)
client.entity.append(client_entity)
Session.add(client)
Session.commit()
今私によると、これは可能であるはずであり、私が私の知恵の終わりにいるので、誰かが助けてくれることを願っています。