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

2024-05-20 13:36:37 发布

您现在位置:Python中文网/ 问答频道 /正文

通常,可以重写get\u context\u data、get\u queryset和get\u object来操作和处理模型对象(这里是“book”)。问题是,如何在过滤完成后获取生成的queryset,并从中提取有用的信息,以显示在页面的其他部分。你知道吗

假设我有一个简单的图书和出版商模型。我正在尝试获取主查询,并对get\u context\u数据对象进行计数。但显然,get\u context在被我覆盖之前获取get\u 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

Tags: thenameselfcitygetmodelscontextlength