On Feb 19, 2014, at 11:57 PM, Bao Niu <[email protected]> wrote: > Please allow me to clarify here. So if attributes on source object u are > different from attributes loaded from database, database will always prevail? > I thought the source object u should represent newer version of the data, > shouldn't it?
All attributes that are present on your source object are copied to the
database object. All attributes that are not present, are not. There is a
difference between an attribute that is “None” and an attribute that is
missing. In python, this corresponds to whether or not you’d see the attribute
actually present in the object’s __dict__.
If I make an object like this:
obj = User(id=1)
the only attribute that object has is, “id”. All other attributes are
non-present. If my user table has a column like “name”, it is only “present”
if I say this:
obj = User(id=1, name=‘some name’)
or if I want it to be “None”:
obj = User(id=1, name=None)
The merge process doesn't do anything with attributes that are missing. You
can quickly see which attributes are present and which are not by just looking
at the __dict__ of your object:
print obj.__dict__
If you’d like to make an object that has all attributes populated with None,
assuming you’re using declarative constructors you can do something like this:
from sqlalchemy import inspect
obj = User(id=1, **dict((attr.key, None) for attr in
inspect(User).attrs if not attr.uselist and attr.key != ‘id’))
Though that doesn’t account for collections, which to initialize as blank
typically accept a collection of a certain type. That line is kind of
awkward, and what should be used instead sort of depends on what you’re trying
to do.
signature.asc
Description: Message signed with OpenPGP using GPGMail
