views:

187

answers:

2

If there are models as below:

class Donation(models.Model):
     user = FKey(User)
     project = FKey(Project)
     ... 

class Campaign(models.Model):
     user = Fkey(User)
     project = FKey(Project)
     ...

class Project(models.Model)
         ...

What is the simplest django ORM query to find a list of all projects that a given user is associated with.

One direct solution is to obtain all the ids of the projects from both models and query the Projects model for the given ids.

But there has to be better solutions.

A: 

I think we can't merge Campaign QuerySet and Donation so we have to do it in 2 steps:

Project.objects.filter(id = Campaign.objects.filter(user = searchedUser))
Project.objects.filter(id = Donation.objects.filter(user = searchedUser))

and now u can divorce in your page Campaign and Donation in what user have part so there is advantage :)

Rin
+2  A: 

The simplest direct ORM query to do this, can be,

from django.db.models import Q

Project.objects.filter(
Q(id__in=Campaign.objects.filter(user=SomeUser).values('project')) | 
Q(id__in=Donation.objects.filter(user=SomeUser).values('project'))
)
simplyharsh