DRF得到的2行比其他行更大

时间:2018-05-28 09:23:36

标签: python django django-rest-framework

我在表格中有一些行,我希望只获得2个记录,其他记录具有更大的计数值。现在根据我的照片计数50和80应该返回。

我应该有product_ids列表(只有2条记录) 比其他人多count ..所以我应该尝试values_list 我知道这是错的我怎么能解决它?

prod_ids = ProductViewCount.objects.all()。aggregate(Max('count'))。values_list('product',flat = True)

这是我的完整代码:

class ViewTopLiked(APIView):
    def get(self, request):
        prod_ids = ProductViewCount.objects.all().aggregate(Max('count')).values_list('product', flat=True)

        obj = Product.objects.filter(product_id__in=prod_ids).order_by('-created_date')

        serializer = ProductSerializer(instance=obj, many=True, context={'request': request})

        return Response(serializer.data)

table img

productViewcount模型: 模型:

class ProductViewCount(models.Model):
    product = models.ForeignKey(Product, on_delete=models.CASCADE, to_field='product_id',
                                related_name='count')

    count = models.IntegerField(null=True, blank=True, default=0)

产品型号:

class Product(models.Model):
    PRO = 'P'
    INTER = 'I'
    BEGINER = 'B'
    ALL = 'A'

    TYPE_CHOICE = ((PRO, 'P'), (INTER, 'I'), (BEGINER, 'B'), (ALL, 'A'))

    product_id = models.AutoField(primary_key=True)
    author = models.ForeignKey(User, on_delete=models.CASCADE, db_index=True)
    title = models.CharField(max_length=200)
    video_length = models.IntegerField(null=True, blank=True)
    mini_description = models.CharField(max_length=1000, null=True, blank=True)
    full_description = models.TextField(null=True, blank=True)
    price = models.IntegerField(null=True, blank=True)
    free = models.BooleanField(default=False)
    video_level = models.CharField(max_length=20, choices=TYPE_CHOICE, default=ALL)
    created_date = models.DateTimeField(auto_now_add=True)
    updated_date = models.DateTimeField(auto_now=True)
    publish = models.BooleanField(default=False)
    draft = models.BooleanField(default=False)
    slug = models.SlugField(allow_unicode=True, null=True, blank=True)
    image = models.FileField(upload_to=upload_to_custom_p, null=True, blank=True)
    lecture = models.IntegerField(null=True, blank=True)

    def __str__(self):
        return self.title

    @property
    def owner(self):
        return self.author

1 个答案:

答案 0 :(得分:2)

对于订购,您可以在产品查询集中使用计数related_name,以便仅前两个元素使用切片[:2]

obj = Product.objects.order_by('-count__count')[:2]

serializer = ProductSerializer(instance=obj, many=True, context={'request': request})

return Response(serializer.data)