我有一个基于班级的视图,向我显示所有餐厅的所有产品,但我想使用request.user.restaurant显示实际餐馆的产品,但这对我不起作用向我展示所有餐厅和所有产品......
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
答案 0 :(得分:0)
您可以使用APIView代替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)
答案 1 :(得分:0)
对于上述情况,我们仅需要覆盖get_queryset
方法。代码如下所示
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