对模型的最终查询集执行额外操作

时间:2014-11-11 09:13:08

标签: python django django-orm

通常,可以覆盖get_context_data,get_queryset和get_object来操作模型对象上的其他工作(AFAIK),这里是“book”。问题是如何在完成过滤后生成任何查询集,并从中提取有用信息,以显示在页面的其他部分。

假设我有一个简单的书籍和出版商模型。我正在尝试获取主要查询,并为get_context_data对象计算它。但显然,get_context在被我覆盖之前获取了get_queryset,因此我的查询不是过滤后的。

# models.py
from django.db import models

class Publisher(models.Model):
    name = models.CharField(max_length=30)
    address = models.CharField(max_length=50)
    city = models.CharField(max_length=60)
    state_province = models.CharField(max_length=30)
    country = models.CharField(max_length=50)
    website = models.URLField()

    class Meta:
        ordering = ["-name"]

    def __unicode__(self):
        return self.name

class Book(models.Model):
    title = models.CharField(max_length=100)
    authors = models.ManyToManyField('Author')
    publisher = models.ForeignKey(Publisher)
    publication_date = models.DateField()



class BookListView(ListView):

    context_object_name = "book"
    model = Book


    def get_queryset(self):
        """ filter the publishers based on city """
        qs = super(BookListView, self).get_queryset()

        city_list = self.request.GET.getlist(u'city', None)

        if len(city_list) > 0:
            qs = qs.filter(publisher__city__iregex=r'(' + '|'.join(city_list) + ')')

        return qs

    def get_context_data(self, **kwargs):
        # Call the base implementation first to get a context
        context = super(PublisherDetailView, self).get_context_data(**kwargs)

        #### How to get the count of the books once filtered in get_queryset

        context['book_list'] = self.model.objects.values('publisher_name').annotate(
            num_cl=Count('publisher')) \
            .order_by("-num_cl")

        return context

1 个答案:

答案 0 :(得分:2)

为什么不直接使用查询集?

context['book_list'] = context['object_list'].annotate(...)

另请注意,您的查询集过滤器非常奇怪。最好使用__in

if city_list:
    qs = qs.filter(publisher__city__in=[city_list])