Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Django:使用特定筛选字段对Queryset进行排序_Django_Sorting_Django Queryset_Annotate - Fatal编程技术网

Django:使用特定筛选字段对Queryset进行排序

Django:使用特定筛选字段对Queryset进行排序,django,sorting,django-queryset,annotate,Django,Sorting,Django Queryset,Annotate,我需要对queryset中的项目进行排序,引入内容的过时。(内容有许多与项目类相关)。 是否可以在注释中按发布日期过滤内容 我的代码在这里适用于每个内容发布日期。我需要annotate函数为“pub_date>'2012-10-10'”工作(例如) 我尝试使用extra()函数进行筛选,但该函数不起作用: self.queryset = self.queryset.extra(select={ 'content': "pub_date > '2012-10-10'"}).annotate(

我需要对queryset中的项目进行排序,引入内容的过时。(内容有许多与项目类相关)。 是否可以在注释中按发布日期过滤内容

我的代码在这里适用于每个内容发布日期。我需要annotate函数为“pub_date>'2012-10-10'”工作(例如)

我尝试使用extra()函数进行筛选,但该函数不起作用:

self.queryset = self.queryset.extra(select={
'content': "pub_date > '2012-10-10'"}).annotate(
Count("content")).order_by("-content__count")

您可以只进行筛选,然后进行注释

self.queryset = Items.objetct.filter(content__pub_date__gt = '2012-10-10')
self.queryset = self.queryset.annotate(
    Count("content")).order_by("-content__count")
假设你的模型是这样的

class Content(models.Model):
    pub_date = models.DateTimeField()

    def __unicode__(self):
        return "%s" % self.id

class Item(models.Model):
    content = models.ManyToManyField(Content)

    def __unicode__(self):
        return "%s" % self.id
在我的测试中,我添加了3个内容和两个项目。id为1的项通过内容多对多与id为1的内容存在关系。id为2的项通过内容多对多与id为2和3的内容存在关系

>>> Item.objects.filter(
        content__pub_date__gt ='2012-10-10').annotate(
        Count("content")).order_by("-content__count")
>>> [<Item: 2>, <Item: 1>]
>>Item.objects.filter(
内容发布日期(2012-10-10)。注释(
计数(“内容”)。按(“-content\u Count”)排序
>>> [, ]

正如所料。

可以,但我的问题有点不同。我想按发布日期筛选内容,然后按内容数排序。对不起,我不明白你的意思。使用我的代码,您可以按发布日期过滤,然后按内容计数排序。我遗漏了什么吗?Content和Item是两个不同的类,有很多关系。所以他们的过滤方式不同。@guillaumekal我编辑原始答案,向您展示它是如何工作的。我认为这是正确的。
>>> Item.objects.filter(
        content__pub_date__gt ='2012-10-10').annotate(
        Count("content")).order_by("-content__count")
>>> [<Item: 2>, <Item: 1>]