从Django Rest框架隐藏数量为0的产品

时间:2019-03-07 18:36:48

标签: django django-rest-framework

如何隐藏数量== 0的产品? 这是我的 models.py

class Product(models.Model):
    title = models.CharField(max_length=255, db_index=True)
    description = models.TextField()
    price = models.DecimalField(default=0.00, max_digits=100, decimal_places=2)
    quantity = models.PositiveIntegerField()
    color = models.CharField(choices=COLOR_CHOICES, default='BLACK', max_length=100)
    category = models.ManyToManyField(Category, related_name='products')

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

    def __str__(self):
        return self.title

    @property
    def instock(self):
        return self.quantity > 0

和我的views.py

class ProductsList(generics.ListAPIView):
    queryset = Product.objects.all().order_by('-id')
    serializer_class = ProductSerializer
    filter_backends = (django_filters.rest_framework.DjangoFilterBackend,)
    filter_class = ProductFilter

1 个答案:

答案 0 :(得分:0)

您可以使用 exclude(field_name = value_to_exclude)排除对象,因此:

 class ProductsList(generics.ListAPIView):
        queryset = Product.objects.all().exclude(quantity=0).order_by('-id')
        serializer_class = ProductSerializer
        filter_backends = (django_filters.rest_framework.DjangoFilterBackend,)
        filter_class = ProductFilter