iteration over fk in django
if I have table like this represented in django model
person
------
id
name
worker
------
personid
jobid
job
---
id
desc
wage
w=Worker.objects.filter(<some sort of filter)
now I want all persons
that are related in w
w
is given I can not use that statement.
eventually I want to return a json string that represents a dict
idperson
as key and {"job":jobid,"wage":wage}
as
one value in list of jobs
for 开发者_开发百科that keyYou should be able to us an in, with any collection of objects you wish. It should look something like:
w = Worker.objects.filter(job__in=Job.objects.filter(somefilterhere))
From here of course you could iterate over your workers and build up your list:
somelist = []
for worker in w:
somelist.append({'person': worker.person.id, 'wage': worker.job.wage})
http://docs.djangoproject.com/en/1.3/topics/db/queries/#following-relationships-backward
Person.objects.filter(worker__id__in=[worker.pk for worker in w])
credit to support
精彩评论