开发者

Pylons + SQLA: One to One Relationship

Newbie question. Pylons 1 + SQLA using declarative style. New to Python.

I have a "master" class called Entity, which "child" classes must belong to for them to be valid. My link to the master class is on the child object level. My issue is that I can't seem to figure out how one creates a child object and create a master object as well as create the link between the objects. I make use of relations for the linking.

Thus I would like 开发者_高级运维to create a ono on one link as below: Entity 1 - Client 1 Entity 2 - Client 2 Entity 3 - Producer 1 Entity 4 - Producer 2 etc.

The code might explain better.

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__

In the controller I try to create a new client and append it an entity, which fails miserably. Please code below.

            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()

Now according to me this should be possible and I hope someone can help as I am at my wits end.


Does this make sense?

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)
    name        = Column(UnicodeText())
    entity_id   = Column(Integer, ForeignKey('entities.entity_id'))
    # Mapper
    entity = relation('Entity', uselist=False, backref='clients')

    def __init__(self, name):
        self.name = name

    def __unicode__(self):
        return self.name
    __str__ = __unicode__



client_name="ClientName"
entitiy_name="EntityName"

client = Client(name=client_name)
client.entity=Entity(name=entitiy_name, description=entitiy_name + " added")

I think that "uselist=False" is useful if you use OneToOne.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜