0

アイテムのクエリセットを並べ替えて、コンテンツの陳腐化を導入する必要があります。(コンテンツはItemクラスに関連付けられたManytoManyです)。注釈内で pub_date によってコンテンツをフィルタリングすることは可能ですか?

私のコードは、コンテンツの公開日ごとにここで機能します。「pub_date > '2012-10-10'」で機能するには、注釈機能が必要です(たとえば)。

self.queryset = Item.objects.all()    
self.queryset = self.queryset.annotate(
                Count("content")).order_by("-content__count")

extra() 関数でフィルタリングしようとしましたが、機能しません:

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

1 に答える 1

0

フィルタリングしてから注釈を付けることができます。

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つのコンテンツと2つのアイテムを追加しました。ID 1のアイテムは、多対多のコンテンツを介してID1のコンテンツと関係があります。ID 2のアイテムは、多対多のコンテンツを介してID2および3のコンテンツと関係があります。

>>> Item.objects.filter(
        content__pub_date__gt ='2012-10-10').annotate(
        Count("content")).order_by("-content__count")
>>> [<Item: 2>, <Item: 1>]

予想通り。

于 2012-10-15T14:59:13.600 に答える