How do you access parent and children relationships through the ORM with a conditional on the parent where record child exist?

微笑、不失礼 提交于 2020-01-05 07:34:08

问题


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?


回答1:


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)



来源:https://stackoverflow.com/questions/15982199/how-do-you-access-parent-and-children-relationships-through-the-orm-with-a-condi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!