Hi!
How should i get the details from B and some content of A using that 
foreign key?

Thanks
Madhu

On Saturday, January 31, 2009 10:37:58 PM UTC+5:30, Daniel Roseman wrote:
>
> On Jan 31, 12:27 pm, Markus <mkn...@gmail.com> wrote: 
> > 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 
>
> 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.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/django-users/-/ZjB35hjPVbYJ.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.

Reply via email to