Can Django make this multiple tables query in a single statement?
Let simplify the problem. Say I have two models:
class Man(models.Model):
# some fields
class Job(models.Model):
man = models.ForeignKey(Man)
# other fields
Here, my logic is that, some man may have a job, some may not. Now I want to make a query to select men with the info if the man have a job.
If I write the query in SQL, then something like:
select m.*, j.id from man m left join job j on m.id=j.id where m.some_condition
So that if j.id
is null, then the man has no job. How to make this query in Django ORM?
men_with_jobs = Man.objects.exclude(job_set=None)
.exclude(job_set=None)
is essentially just syntactic sugar to say .filter(job_set__isnull=False)
(which kind of is an instance of following reverse relationships), where job_set
is the implicit name of the reverse relationship from Man
back to the Job
foreignkey.
This will leave you with a queryset containing only Man
instances that have at least one Job
instance referencing them.