首页 > 模型B中有外键联系到模型A,通过什么样的 ORM 查询语句能够过滤A表中的数据在 B 中有或者没有记录的 ?

模型B中有外键联系到模型A,通过什么样的 ORM 查询语句能够过滤A表中的数据在 B 中有或者没有记录的 ?

表格模型如下:

class Document(models.Model):
    title = models.CharField()
    content = models.TextField()
    
class File(models.Model):
    doc = models.ForeignKey(Document)
    name = models.CharField()
    path = models.CharField()
    

一般这样操作的

d1 = Document.objects.create(title='title1',content='content1')
d2 = Document.objects.create(title='title2',content='content2')
f1 = File.objects.create(doc=d1,name='name1',path='path1')

于是d1就有了附件f1,d2是没有附件的。

d1.file_set.all()
:[f1]
d2.file_set.all()
:[]

我想通过这样的语句来过滤出所有有附件或者没有附件的文件。

Document.objects.filter(`file_set__isnull=True\Flase`)    

是不是无法通过 Django 的 ORM 来直接完成?或者要修改表结构?

直接用 sql 语句没什么问题

SELECT * FROM `document` LEFT JOIN `file` on `office_document`.`id` = `file`.`doc_id` where `name` is NULL;

https://docs.djangoproject.com/en/1.9/ref/models/fields/#django.db.models.ForeignKey.related_query_name


Document.objects.filter(file__doc__isnull=True)    
【热门文章】
【热门文章】