django 使用DRF中的queryset过滤当前用户产品返回[]

pobjuy32  于 2022-12-01  发布在  Go
关注(0)|答案(1)|浏览(146)

我正在尝试筛选与用户链接的产品列表。我希望只显示当前用户的产品,而不是列出所有产品。
我试过这个

class ProductCreateList(generics.ListCreateAPIView):
    serializer_class = ProductSerializer

    def get_queryset(self):
        user = self.request.user
        return Product.objects.filter(user=user.id)

serializers.py

class ProductSerializer(serializers.ModelSerializer):
    class Meta:
        model = Product
        fields = ['id', 'user', 'name', 'imgUrl', 'selling_price', 'actual_price', 'quantity', 'get_profit']

models.py

class Product(models.Model):
    user = models.ForeignKey('accounts.Account', on_delete=models.CASCADE, default=1)
    name = models.CharField(max_length=100, null=True, blank=True)
    imgUrl = models.TextField(default='')
    selling_price = models.FloatField(null=True, blank=True)
    actual_price = models.FloatField(null=True, blank=True)
    quantity = models.IntegerField()

当我试图执行端点时,我得到了[]对象。我的错误是什么?

vmpqdwk3

vmpqdwk31#

有几个错误,主要是在你看来.我做了以下几点:
models.py

from django.db import models
from django.contrib.auth import get_user_model

class Product(models.Model):
    user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE, default=1)
    name = models.CharField(max_length=100, null=True, blank=True)
    imgUrl = models.TextField(default='')
    selling_price = models.FloatField(null=True, blank=True)
    actual_price = models.FloatField(null=True, blank=True)
    quantity = models.IntegerField()

    class Meta:
        db_table = 'product'

serializers.py:移除'get_profit'字段或实作序列化程式方法字段

from rest_framework import serializers
from core.models import Product

class ProductSerializer(serializers.ModelSerializer):
    class Meta:
        model = Product
        fields = ['id', 'user', 'name', 'imgUrl', 'selling_price', 'actual_price', 'quantity']

views.py:若要依使用者筛选,请使用authentication_classespermission_classes,确保使用者已通过验证且具有验证权限。请使用filter_queryset拦截,依使用者筛选您的查询集。

from rest_framework.authentication import SessionAuthentication, BasicAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework import generics
from core.api.serializers import ProductSerializer
from core.models import Product

class ProductCreateList(generics.ListCreateAPIView):
    authentication_classes = [SessionAuthentication, BasicAuthentication]  
    permission_classes = [IsAuthenticated]

    serializer_class = ProductSerializer
    queryset = Product.objects.all()

    def filter_queryset(self, queryset):
        queryset = queryset.filter(user=self.request.user)
        return super().filter_queryset(queryset)

相关问题