Reputation: 67
class User(models.Model):
name = models.EmailFiled()
class Product(models.Model):
title = models.CharField(max_length=50)
is_active = models.BooleanField(default=True)
class Cart(models.Model):
product = models.ManyToManyField(Product)
class Order(models.Model):
user = models.ForeignKey(User,on_delete=models.CASCADE)
cart = models.ForeignKey(Cart,on_delete=models.CASCADE)
We have multiple products. some of them are active=False the other ones are True. I should take the products which is active=true requesting user.
Upvotes: 1
Views: 4729
Reputation: 2045
You are looking for the ability to filter results of a ViewSet
based on your active
flag. I highly recommend you to read DRF Filtering documentation
You simply need to add to your ViewSet
or APIView
the following fields
from django_filters.rest_framework import DjangoFilterBackend
class ProductList(generics.ListAPIView):
queryset = Product.objects.all()
serializer_class = ProductSerializer
# Add Filtering Backend
filter_backends = [DjangoFilterBackend]
# Add filtering fields (Default behavior is to exact match provided values)
filterset_fields = ['is_active']
and now in your request, you should have the query param
http://example.com/api/products?is_active=1
Upvotes: 4
Reputation: 476659
You can obtain the Product
s that are active and in the Cart
of a user with:
Product.objects.filter(is_active=True, cart__order__user=my_user)
Upvotes: 0