質問

I have the following two classes:

class user(Base):
   ....
   id=Column(Integer, primary_key=True)
   address=relationship('Address',backref='user')

class Address(Base):
   ...
   IsItAssgined=False
   user_id=Column(Integer, ForeignKey('user.id'))

Lets create two instances of these classes:

Addr=Address()
Tom=User()

I would like the following behaviour: upon appending the Addr to the User, The field IsItAssigned in the Address gets updated to True, i.e.

Tom.address.append(Addr)
print Addr.IsItAssigned 
-> to be True

I don't know how to use descriptors here if possible.

役に立ちましたか?

解決

I'd use a property for that, one that tests if the user_id column is not NULL. A column_property() seems appropriate here:

from sqlalchemy.orm import column_property

class Address(Base):
   ...
   user_id = Column(Integer, ForeignKey('user.id'))
   IsItAssigned = column_property(user_id != None)

Now IsItAssigned will be either True or False. Alternatively, use a hybrid property:

from sqlalchemy.ext.hybrid import hybrid_property

class Address(Base):
   ...
   user_id = Column(Integer, ForeignKey('user.id'))

   @hybrid_property
   def IsItAssigned(self):
       return self.user_id != None

A hybrid property has the advantage of being usable in a query as well. Last but not least, for this case, perhaps an ordinary property would do too, it'll only work on already loaded instances though:

class Address(Base):
   ...
   user_id = Column(Integer, ForeignKey('user.id'))

   @property
   def IsItAssigned(self):
       return self.user_id is not None

I'd use a different name, though. assigned might be better; the Python style guide (PEP 8) advocates the lower_case_with_underscores for methods and instance attributes.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top