You will probably find it easier to search from the User model, since you need a Users list that has both jobs. Django automatically adjusts the properties of your models, which allow you to access related models from both model instances and database queries.
Assuming you configured your models as follows:
from django.db import models class User(models.Model): name = models.CharField(max_length=25) def __repr__(self): return '<User: %s>' % self.name class Job(models.Model): name = models.CharField(max_length=25) def __repr__(self): return '<Job: %s>' % self.name class UserJob(models.Model): user = models.ForeignKey(User) job = models.ForeignKey(Job) def __repr__(self): return '<UserJob: %s %s>' % (self.user.name, self.job.name)
And write it as follows:
u1 = User.objects.create(name='u1') u2 = User.objects.create(name='u2') u3 = User.objects.create(name='u3') a = Job.objects.create(name='a') b = Job.objects.create(name='b') c = Job.objects.create(name='c') UserJob.objects.create(user=u1, job=a) UserJob.objects.create(user=u2, job=a) UserJob.objects.create(user=u2, job=b) UserJob.objects.create(user=u3, job=a) UserJob.objects.create(user=u3, job=c)
The following query will return you to user 3, who is the only user who has both "Job a" and "Job c":
u = User.objects.filter(userjob__job=a).filter(userjob__job=c)
(or, if you prefer to reference tasks by name rather than an instance of the task):
u = User.objects.filter(userjob__job__name='a').filter(userjob__job__name='c')
You can see how Django allows you to move related fields from the User model to the double-labeled UserJob model (Django docs here: http://docs.djangoproject.com/en/1.2/topics/db/queries/#lookups-that- span relationships .
Once you bring the User object back, you can also access UserJob instances using the relationship properties that Django adds to the model:
u = User.objects.filter(userjob__job__name='a').filter(userjob__job__name='c') jobs = u.userjob_set.all()
Jarret hardie
source share