代码之家  ›  专栏  ›  技术社区  ›  devmrh

DRF获得2行,计数比其他行大

  •  1
  • devmrh  · 技术社区  · 6 年前

    我在表中有一些行,我只想得到2条具有比其他行更大的计数值的记录。现在根据我的照片,50和80应该会回来。

    我应该有一个产品ID列表(只有2条记录) 有 count 比其他人更多……所以我应该试试价值观清单 我知道这是错误的,我该怎么修?

    prod_id=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

    产品视图计数模型: 模型:

    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 回复  |  直到 6 年前
        1
  •  2
  •   neverwalkaloner    6 年前

    您可以使用count进行订购 related_name 在产品查询集中,要仅获取前两个元素,请使用切片 [:2] :

    obj = Product.objects.order_by('-count__count')[:2]
    
    serializer = ProductSerializer(instance=obj, many=True, context={'request': request})
    
    return Response(serializer.data)