恢复Django示例:
from django.db import models
class Publication(models.Model):
title = models.CharField(max_length=30)
class Article(models.Model):
headline = models.CharField(max_length=100)
publications = models.ManyToManyField(Publication)
如何获取所有没有出版物的文章?
Article.objects.filter(...)
答案 0 :(得分:0)
将publications
指定为无:
Article.objects.filter(publications=None)
示例:
>>> p1 = Publication.objects.create(title='1')
>>> p2 = Publication.objects.create(title='2')
>>> a1 = Article.objects.create(headline='a')
>>> a2 = Article.objects.create(headline='b')
>>> a3 = Article.objects.create(headline='c')
>>> a1.publications.add(p1)
>>> a1.publications.add(p2)
>>> a3.publications.add(p1)
>>> Article.objects.filter(publications=None)
[<Article: Article object>]
>>> _[0].headline
u'b'
答案 1 :(得分:0)
Article.objects.filter(publications=None)
将blank = True定义为使用publication字段进入文章模型,否则它将不允许您创建没有发布的文章。
publications = models.ManyToManyField(Publication, blank=True)