Home > Blockchain >  How can get products for active owners (users) only with Django Rest Framework?
How can get products for active owners (users) only with Django Rest Framework?

Time:12-02

I'm creating an e-commerce API with DRF. I would like to retrieve and display only active products from active owners (users) using a ModelViewSet How can I do this? Here is my code :

views.py

class ProductViewSet(viewsets.ModelViewSet):
    serializer_class = ProductSerializer
    parser_classes = (MultiPartParser, FormParser)
    search_fields = ['title', 'description']
    ordering_fields = ['price', 'last_update']
    permission_classes = [permissions.IsAuthenticatedOrReadOnly, IsVendorOrReadOnly, IsOwnerOrReadOnly]

    def get_queryset(self):
        return Product.objects.filter(is_active=True)

        # WHEN I'M USING THIS COMMENT CODE, I CAN'T RETRIEVE ONE PRODUCT BY PK
        # products = Product.objects.all()
        # new_products = []
        # for p in products:
        #     if p.owner.is_active and p.is_active:
        #         new_products.append(p)
        # return new_products

    def perform_create(self, serializer):
        serializer.save(owner=self.request.user)

CodePudding user response:

if u have a model like this:

class Prooduct(m.Model):
    ...
    is_active = m.BooleanField()
    owner = m.ForeingKey(User, ...)

Then on the get_queryset method

def get_queryset(self)

    return Product.objects.filter(is_active = True, owner__is_active = True)

this would return all products that are active and the owner of the product is active as well.

  • Related