如何在Django中为一个多对多属性的模型创建一个过滤器queryset



描述:-我想过滤所有作者是john &保罗。下面是我正在使用的模型。谁能解决这个问题?

class Blog(models.Model):
    name = models.CharField(max_length=100)
    tagline = models.TextField()
    def str__(self):              # unicode__ on Python 2
     return self.name
class Author(models.Model):
     name = models.CharField(max_length=200)
     email = models.EmailField()
     def str__(self):              # unicode__ on Python 2
       return self.name
class Entry(models.Model):
     blog = models.ForeignKey(Blog)
     headline = models.CharField(max_length=255)
     body_text = models.TextField()
     pub_date = models.DateField()
     mod_date = models.DateField()
     authors = models.ManyToManyField(Author)
     n_comments = models.IntegerField()
     n_pingbacks = models.IntegerField()
     rating = models.IntegerField()
    def str__(self):              # unicode__ on Python 2
      return self.headline

只过滤两次(如@dnit13所说)。这是唯一的办法

Entry.objects.all().filter(authors__name='john').filter(authors__name='paul')

如果作者列表是动态的:

authors = ['john', 'paul']
entries = Entry.objects.all()
for author in authors:
    entries = entries.filter(authors__name=author)

使用两次滤镜

Entry.objects.filter(authors__name='john').filter(authors__name='paul')

相关内容

  • 没有找到相关文章

最新更新