简体   繁体   中英

Django rest framework API with filter

Models.py

Categories:

class Category_product(models.Model):
    category_name = models.CharField(max_length=200, unique=True)

    def __str__(self):
        return self.category_name  

Products:

class Warehouse(models.Model):
    category_product = models.ForeignKey(
    Category_product, on_delete=models.CASCADE)
    product_name = models.CharField(max_length=200, unique=True)
    condition = models.BooleanField(default=False)
    amount = models.IntegerField()
    barcode = models.BigIntegerField()
    f_price = models.CharField(max_length=255, null=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.product_name

urls.py

   path('products-list/', views.WarehouseList.as_view()),

Views.py

class WarehouseList(generics.ListCreateAPIView):
    queryset = Warehouse.objects.all()
    serializer_class = WarehouseSerializer

Serializers.py

# SERIALIZER OF CATEGORY PRODUCTS
class Category_productSerializer(serializers.ModelSerializer):
    class Meta:
        model = Category_product
        fields = ['id', 'category_name']


# SERIALIZER OF WAREHOUSE
class WarehouseSerializer(serializers.ModelSerializer):
category_name = serializers.ReadOnlyField(
    source='category_product.category_name')

def get_serializer(self, *args, **kwargs):
    if isinstance(kwargs.get('data', {}), list):
        kwargs['many'] = True
    return super(Category_productSerializer, self).get_serializer(*args, **kwargs)

class Meta:
    model = Warehouse
    fields = ['id', 'category_product', 'category_name', 'condition',
              'product_name', 'amount', 'barcode', 'f_price', 'created_at', 'updated_at']

I want to get products by exact category

For example: I have product category

{
"id": 1 
"category_name": "Electronics"
}

If I send GET request to api/products-list/?cat=1 I want to get products which have this category

Create a get_queryset method as follow.

class WarehouseList(generics.ListCreateAPIView):

    queryset = WareHouse.objects.all()
    serializer_class = WarehouseSerializer

    def get_queryset(self):
       cat = self.request.query_params.get('cat', None)       
       if cat is not None:
            self.queryset = self.queryset.filter(category_product__id=cat)
       return self.queryset

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