0

继续 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(...) 
4

2 回答 2

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'
于 2013-10-30T04:50:44.393 回答
0
Article.objects.filter(publications=None)

将带有出版物字段的空白=真定义到文章模型中,否则它将不允许您创建没有出版物的文章。

publications = models.ManyToManyField(Publication, blank=True)  
于 2013-10-30T05:02:18.367 回答