我想使用django-filter创建一个FilerSet,该文件集具有字段A(Minutes.case)的不同结果,并按字段B(case__case_filed_date)排序。数据库是PostgreSQL。
MinutesListView类中的注释行是我尝试过的东西(在各种配置中)。
models.py
class Case(models.Model):
case_filed_date = models.DateField()
case_number = models.CharField(max_length=25, unique=True)
as_of_timestamp = models.DateTimeField()
def __str__(self):
return self.case_number
class Minutes(models.Model):
case = models.ForeignKey(Case, on_delete=models.CASCADE)
minute_entry_text = models.TextField(blank=True, null=True)
minute_entry_date = models.DateField(blank=True, null=True)
minute_entry_type_text = models.CharField(max_length=255, blank=True, null=True)
filters.py
class MinuteFilterSet(df.FilterSet):
case__case_number = df.CharFilter(lookup_expr='icontains', label='Case Number', distinct=True)
minute_entry_text = df.CharFilter(lookup_expr='icontains', label='Minutes Text')
class Meta:
model = Minutes
fields = ['minute_entry_text']
order_by = ['-case__case_filed_date']
views.py:
class FilteredListView(ListView):
filterset_class = None
def get_queryset(self):
# Get the queryset however you usually would. For example:
queryset = super().get_queryset()
# Then use the query parameters and the queryset to
# instantiate a filterset and save it as an attribute
# on the view instance for later.
self.filterset = self.filterset_class(self.request.GET, queryset=queryset)
# Return the filtered queryset
return self.filterset.qs
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
# Pass the filterset to the template - it provides the form.
context['filterset'] = self.filterset
return context
class MinutesListView(FilteredListView):
filterset_class = filters.MinuteFilterSet
paginate_by = 25
# ordering = '-case__case_filed_date'
# queryset = Minutes.objects.all()
queryset = Minutes.objects.distinct('case')
当前代码显示了不同的,无序的结果。当我能够获得有序的结果时,案例(case_number)就重复了。我已经阅读了有关Django / PostGreSQL中与order_by()的distinct()有关的文档,但仍然缺少某些内容。