Merging results from two tables

2,206 views
Skip to first unread message

Markus

unread,
Jan 31, 2009, 7:27:46 AM1/31/09
to Django users
Hi

just starting to use Django, am stuck with the following problem:

Given

class A(models.Model):
...some fields...

class B(models.Model):
A = models.ForeignKey(A)
....some fields...

I would like to generate a Queryset that returns values from both
tables, ie in SQL

SELECT A.field1, A.field2, B.field1, B.field2
FROM A, B
WHERE A.id = B.A_id AND some filter on A AND .. some further
conditions to ensure only one row from table B is matched

So far, I found a way to achieve this using the extra operator:

A.objects.filter(..some filter on A..).extra(select={'field1': "select
B.field1 from B ...", 'field2': 'select B.field2 from B ..."})

This quickly becomes clumsy as the number of fields in table B
increases. There must be a better way? As I couldnt find anything in
the documentation, I would appreciate a nudge in the right direction.

Thanks
Markus

Daniel Roseman

unread,
Jan 31, 2009, 12:07:58 PM1/31/09
to Django users
You haven't explained exactly what you want from B - all the values,
or just the ones that have values in A, or just the ones for a single
value of A?

If you just want all the associated B for each value of A, then a
simple queryset will do the trick.
qs = A.objects.all()
for a in qs:
print a.b_set.all()

You can make this a bit more efficient by calling the initial queryset
with select_related.
qs = A.objects.all().select_related()

I would suggest reading the section on related objects again:
http://docs.djangoproject.com/en/dev/topics/db/queries/#related-objects
--
DR.

Markus

unread,
Feb 1, 2009, 4:46:39 PM2/1/09
to Django users
Thanks, that did the trick!!

On Jan 31, 6:07 pm, Daniel Roseman <roseman.dan...@googlemail.com>
wrote:

Madhu

unread,
Jul 24, 2012, 2:51:39 AM7/24/12
to django...@googlegroups.com
Hi!
How should i get the details from B and some content of A using that foreign key?

Thanks
Madhu
Reply all
Reply to author
Forward
0 new messages