简体   繁体   中英

how to filter with django rest framework?

I'm using django rest framework in my project and I want to have filtering on my products. i filter products with category name and popular. but i want to filter products that have discount too.

this is my model:

class Product(models.Model):
    category = models.ManyToManyField(Category, related_name='products')
    name = models.CharField(max_length=500)
    slug = models.SlugField(max_length=500, allow_unicode=True, unique=True)
    image = models.ImageField(upload_to='products_pic/%Y/%m/%d/', null=True, blank=True)
    description = models.TextField(null=True, blank=True)
    price = models.PositiveIntegerField()
    discount = models.PositiveIntegerField(null=True, blank=True)
    available = models.BooleanField(default=True)
    popular = models.BooleanField(default=False)
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)
    comments = GenericRelation(Comment)

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

    def __str__(self):
        return self.name

there is a problem here. discount is a integer field and i want to filter products with boolean discount. i mean i want to filter products that have discount or not. it is not important how much discount they have.

this is my view:

class search(generics.ListAPIView):
    queryset = Product.objects.filter(available=True)
    serializer_class = ProductSerializer
    permission_classes = (permissions.AllowAny,)
    filter_backends = [DjangoFilterBackend, filters.SearchFilter]
    filter_fields = ['category__name', 'popular']
    search_fields = ['name', 'category__name', 'description']

You can create a filterset backends for DjangoFilterBackend. Docs

filters.py

from django_filters import rest_framework
class ProductFilter(rest_framework.FilterSet):
    discount= rest_framework.BooleanFilter(method='get_discount')

    class Meta:
        fields = ("discount", "category__name", "popular")
        model = Product
    
   def get_discount(self, queryset, name, value):
        return queryset.filter(discount__isnull=False)

After that, you should set your filter class to your view's attr.

class search(generics.ListAPIView):
    queryset = Product.objects.filter(available=True)
    serializer_class = ProductSerializer
    permission_classes = (permissions.AllowAny,)
    filter_backends = [DjangoFilterBackend, filters.SearchFilter]
    filterset_class= ProductFilter
    search_fields = ['name', 'category__name', 'description']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM