Gelonida's response. Additionally, Use Q to create more logically
advanced queries. I find your language difficult to gather what query
you are looking for exactly, but here is an example of what I think
you might mean:
from django.db.models import Q
the_Ds = D.objects.all().filter(b=B)
the_Es = E.objects.all().filter(c=C)
combined = the_Ds | the_Es
# Other Example (an & requires both constraints to be met, and an Or
will include the set of all matches.
the_As = A.objects.all().filter(Q(constraint1) & Q(constraint2))
the_Bs = B.objects.all().filter(Q(constraint1) | Q(constraint2))
-Matteius
Don't overlook how powerful this is because Django has Manager classes
so you can make your constraints refer to both local properties and
foreign key constraints as well as properties within the foreign key
lookups. You may find that you wish to edit your schema relationship,
perhaps by pointing backwards or reversing the relationship. It is
hard to say with the categorical A, B, C, D example, but hope this
helps and Good Luck!
On Aug 27, 3:47 pm, Gelonida N <gelon...@gmail.com> wrote:
> On 08/27/2011 11:39 AM, graeme wrote:
>
>
>
> > I have a some models related link this:
>
> > A has a foreign key on B which has a foreign key on C
>
> > I also have D with a foreign key on B, and E with a foreign key of C
>
> > If I do A.filter(**args).select_related() I will get all the As, Bs,
> > and Cs I want.
>
> > How do I get the Ds with a foreign key on a B in my queryset
> > (preferably filtered) and all Es with a foreign key on C (also
> > preferably filtered)
>
> > The best I have been able to come up with is to query for all the the
> > Ds and Es I want, and combine them with the Bs and Cs in the view.
>
> > I have a similar problem with another site, except that there not
> > every B I want has an A with a foreignkey pointing to it, so I cannot
> > just do select_related on A.
>
> > I am not worried about doing an extra query or two per page. What I
> > want to avoid is doing an extra query for each object in a lengthy
> > list.
>
> You can 'or' two query sets with the '|' operator
>
> so do
> queryset1 = Mymodel.objects.all().filter(...)
> qyeryset2 = Mymodel.objects.all().filter(...)
>
> combined = queryset1 | queryset2
--
You received this message because you are subscribed to the Google Groups "Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to django-users+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
No comments:
Post a Comment