如何通过ORM访问父母和子女关系,并以条件对父母存在记录小孩存在? [英] How do you access parent and children relationships through the ORM with a conditional on the parent where record child exist?

查看:137
本文介绍了如何通过ORM访问父母和子女关系,并以条件对父母存在记录小孩存在?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过Django ORM创建一个查询,这是一个直接的连接。我试图从父表中提取在子表中有条目的记录,另外我想在父表上添加一个条件。

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.

这里是示例模型:

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) 

SQL将如下所示:

Select * from Reporter 
JOIN Article ON Article.reporter_id = Reporter.id 
where Reporter.last_name="Jones"

我使用Django ORM构造上面的查询?

How do I construct the query above using the Django ORM?

推荐答案

这将做一个内部连接并返回记者:

This will do an inner join and return reporters:

Reporter.objects.filter(last_name='Jones', article__isnull=False)

(它也会添加一个无害的 article.id IS NOT NULL WHERE

(it will also add a harmless article.id IS NOT NULL to the WHERE)

这篇关于如何通过ORM访问父母和子女关系,并以条件对父母存在记录小孩存在?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆