i have a class based view that display me all the products for all the restaurants , but i want to display just the products of the actual restaurants using request.user.restaurant but that is don't work for me that is display me all the restaurants and all the products ....
class MealListCreateAPIView(generics.ListCreateAPIView):
queryset = Meal.objects.all()
serializer_class = MealSerializer
permission_classes = [permissions.IsAuthenticatedOrReadOnly]
def get_queryset(self):
request = self.request
qs = Meal.objects.all()
query = request.GET.get('q')
if query is not None:
qs = qs.filter(name__icontains=query, description__icontains=query)
return qs
def get_restaurant(self):
qs = Meal.objects.all()
query = request.GET.get('')
if query is not None:
qs = qs.filter(restaurant = self.request.restaurant.user).order_by("-id")
return qs
you can use APIView instead of ListCreatAPIView
class MealListAPIView(APIView):
serializer_class = MealSerializer
def get(self, request):
qs = Meal.objects.all()
query = request.GET.get('')
if query is not None:
qs = qs.filter(restaurant = self.request.restaurant.user).order_by("-id")
return self.serializer_class(data=qs, many=True)
For above case we only need to override the get_queryset
method. The code will look like below
class MealListCreateAPIView(generics.ListCreateAPIView):
queryset = Meal.objects.all()
serializer_class = MealSerializer
def get_queryset(self):
queryset = self.queryset.filter(restarent=self.request.user.restaurant)
q = self.request.GET.get('q')
if q:
queryset = queryset.filter(name__icontains=q, description__icontains=q)
return 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.