具有组合过滤器的不同应用模型之间的查询集

时间:2016-08-02 07:49:52

标签: python django

我正在尝试将Django-hitcount order_by(' -hits')过滤器与我自己的自定义模型相结合。我需要获得最多5个项目的最大命中数。但无法使其适用于主页视图。

以下是代码:

产品/ models.py:

class ProductQuerySet(models.query.QuerySet):
    def active(self):
        return self.filter(active=True)

class ProductManager(models.Manager):
    def get_queryset(self):
        return ProductQuerySet(self.model, using=self._db)

    def all(self, *args, **kwargs):
        return self.get_queryset().active()

    def get_related(self, instance):
        products_one = self.get_queryset().filter(categories__in=instance.categories.all())
        products_two = self.get_queryset().filter(default=instance.default)
        qs = (products_one | products_two).exclude(id=instance.id).distinct()
        return qs


class Product(models.Model):
    title = models.CharField(max_length=120)
    description = models.TextField(blank=True, null=True)
    price = models.DecimalField(decimal_places=2, max_digits=20)
    active = models.BooleanField(default=True)
    categories = models.ManyToManyField('Category', blank=True)
    default = models.ForeignKey('Category', related_name='default_category', null=True, blank=True)
    hits = models.ForeignKey(HitCount)

    objects = ProductManager()

    class Meta:
        ordering = ["-title"]

Django的hitcount / models.py:

class HitCount(models.Model):

    hits = models.PositiveIntegerField(default=0)
    modified = models.DateTimeField(auto_now=True)
    content_type = models.ForeignKey(
        ContentType, related_name="content_type_set_for_%(class)s", on_delete=models.CASCADE)
    object_pk = models.PositiveIntegerField('object ID')
    content_object = GenericForeignKey('content_type', 'object_pk')

    objects = HitCountManager()

    class Meta:
        ordering = ('-hits',)

家/ views.py:

from products.models import Product
from hitcount.models import Hitcount

trending = Product.objects.all().order_by('-hits')[:5]

我创建了一个外键来将hitcount与我的产品模型集成。请帮助我如何获得最多5个产品的最高命中率。我使用了MAX聚合选项,但它没有用。我是djagno的新手,所以寻找解决方案。

1 个答案:

答案 0 :(得分:0)

您可以使用.annotate()函数与Max进行计算,然后对其进行排序并限制前五个结果:

>>> products = Product.objects.all()
>>> products = products.annotate(hits=Max('hits__hits'))
>>> products = products.order_by('-hits')[:5]
>>> # Displaying the results
>>> products.values('hits')
<ProductQuerySet [{'hits': 30}, {'hits': 8}, {'hits': 7}, {'hits': 6}, {'hits': 4}]>

如果您对此工作有更多疑问,请查看django文档:https://docs.djangoproject.com/en/2.0/topics/db/aggregation/#cheat-sheet