在Filter中使用自定义反向管理器

时间:2015-05-29 18:10:42

标签: django django-models django-queryset django-orm django-managers

鉴于我有:

class Publisher(Model):
  pass

class Author(Model):
  name = models.CharField(...)
  publisher = models.ForeignKey(Publisher)
  is_alive = models.BooleanField(...)
  objects = models.Manager()  # Default Manager
  alives = AliveManager()    # Custom Manager

现在我可以使用:

过滤
Publisher.objects.filter(author__name='xxx', author__is_alive=True)

无论如何,我的问题是在过滤器语句中利用custom reverse manager吗?

publisher.author_set(manager="alives")

给了我一个给定的出版商。

1 个答案:

答案 0 :(得分:2)

我想这是文档中的相关内容:

  

[...] get_queryset()方法中的默认过滤,该过滤将应用于all()调用。

class AliveManager(Manager):
    def get_queryset(self):
        qs = super(AliveManager, self).get_queryset()
        return qs.filter(is_alive=True)

class Author(Model):
    name = models.CharField(...)
    publisher = models.ForeignKey(Publisher)
    is_alive = models.BooleanField(...)
    objects = models.Manager()  # Default Manager
    alives = AliveManager()    # Custom Manager


# returns all alive authors
publisher.author_set(manager='alives').all()
# filters through alive authors
publisher.author_set(manager='alives').filter(author__name='xxx')