0
일반적으로 get_context_data, get_queryset 및 get_object를 재정 의하여 모델 오브젝트 (여기서는 "book")에서 다른 작업 (AFAIK)을 조작하고 수행 할 수 있습니다. 질문은 필터링이 완료된 후에 어떤 쿼리 세트를 생성하고 유용한 정보를 추출하여 페이지의 다른 부분에 표시 할 수있는 방법입니다.모델의 최종 쿼리 세트에 대한 추가 연산 수행
내가 책과 게시자의 간단한 모델을 가지고 있다고 가정 해 보겠습니다. 나는 메인 쿼리를 얻으려고 노력하고, get_context_data 객체를 위해 그것에 카운트를 둔다. 하지만 분명히, get_context는 get_queryset이 나에 의해 오버라이드 (override)되기 전에 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
완벽! 내가 paginator 객체를 사용하여 끝내 었는데, 그 이유는 paginator 객체가 내부에있는 요소의 전체 수를 보았고, 잘린 요소가 아닌 것을보아야했기 때문입니다. 많은 감사합니다! –