I am very much new in django restframework,I tried to create a search api.
I have 2 models designed
class Category(models.Model):
name = models.CharField(max_length=200)
def __str__(self):
return self.name
class Product(models.Model):
product_name = models.CharField(max_length=255)
product_Comments = models.CharField(max_length=255)
size = models.CharField(max_length=10, null=True)
product_Status = models.BooleanField(default=True)
category = models.ForeignKey(Category, on_delete=models.CASCADE, null=True)
def __str__(self):
return self.product_Description
I want to create a rest API, in which I can search the category and based on the search i want to list the product which related to that category. How can I do it.
My Views.py
class productList(generics.ListAPIView):
serializer_class = productSerializer
def get_queryset(self):
queryset = Product.objects.all()
search = self.request.query_params.get('search', None)
if search is not None:
queryset = queryset.filter(product_name__icontains=search)
my urls
path('product_search/',views.productList.as_view()),
You're almost there, you just need to add filtering .
Also, you almost never need to override the get()
method of a generic view. Look for the method that let's you do the least amount of work. For any view, you will do most work in get_queryset
and a view specific method:
list()
create()
retrieve()
perform_update()
perform_destroy()
The rest can be customized by setting the correct class attributes. There are very few cases where it is necessary to override a view's "get" or "post" methods.
So, get_queryset
is the place to modify the collection of objects that you are going to work on. This is perfect for filtering and thus search. A lot of work is already available in DRF and you can use it:
class productList(generics.ListAPIView):
serializer_class = productSerializer
def get_queryset(self):
queryset = Product.objects.all()
search = self.request.query_params.get('search', None)
if search is not None:
queryset = queryset.filter(category__name__icontains=search)
# don't forget to return the queryset
return queryset
For filtering the Products based on category name is,
Product.object.filter( category__name = 'category_name')
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.