Reputation: 82
I am trying to create a query through the Django ORM which is a straight join. I am trying to extract only records from parent table that have an entry in the child table, In addition, I would like to add a conditional on the parent table.
Here are the sample model:
class Reporter(models.Model):
first_name = models.CharField(max_length=64)
last_name = models.CharField(max_length=64)
class Article(models.Model):
pub_date = models.DateField()
headline = models.CharField(max_length=200)
content = models.TextField()
reporter = models.ForeignKey(Reporter)
The SQL would look as follows:
Select * from Reporter
JOIN Article ON Article.reporter_id = Reporter.id
where Reporter.last_name="Jones"
How do I construct the query above using the Django ORM?
Upvotes: 1
Views: 120
Reputation: 62928
This will do an inner join and return reporters:
Reporter.objects.filter(last_name='Jones', article__isnull=False)
(it will also add a harmless article.id IS NOT NULL
to the WHERE
)
Upvotes: 3