Newbie Query Question - querying objects in related table ina python way

8 views
Skip to first unread message

Darren

unread,
Feb 29, 2012, 7:21:08 AM2/29/12
to SQLElixir
Hi,

I have a simple 1:many table relationship (say, user, adresses), and I
can say thing like the following (syntax wrong, just psuedo code):

jack = User(name="Jack")
jack.addresess.append(Address(postcode=345)
jack.addresess.append(Address(postcode=1234))

Then working with jack, I can say things like
jack.adresses[0] and get the first appended item, and [-1] to get last
(not sure if this is guarateed), just like they were python lists

To find address with postcode=345, I have to

User.query.filter(....... messy filter to specify which user and post
code)

Is there a more natural (python) way where I can do a query on that
list of jack.adresses, say:

jack.adresses.query(postcode == 345)
or
jack.addresses.postcode[345]

Thanks

Darren






Darren Steven

unread,
Feb 29, 2012, 7:57:44 AM2/29/12
to SQLElixir
OK, may have found it. In the LHS of the relation,

adresses = OneToMany('Address', lazy='dynamic') enables this behaviour

so jack.adresses.filter(postcode == 123) is valid now (rather than
raising an exception about 'Instrumented List' has no filter attribute

Which is a bit less verbose, and readable.

Darren

Reply all
Reply to author
Forward
0 new messages