django-rest-framwork尝试获取字段值时出现AttributeError

dev*_*mrh 5 python django django-rest-framework

我想用join product_ratings table获取所有产品表值。我做了这样的事情,但是这段代码给了我AttributeError ...

产品序列化程序中的product_ratings = ProductRatingSerializer(many = True),并在字段中使用了此值,但它不起作用:

其完整的错误消息:

Got AttributeError when attempting to get a value for field `product_ratings` on serializer `ProductSerializer`.
The serializer field might be named incorrectly and not match any attribute or key on the `Product` instance.
Original exception text was: 'Product' object has no attribute 'product_ratings'.
Run Code Online (Sandbox Code Playgroud)

查看:

class StoreApiView(mixins.CreateModelMixin, generics.ListAPIView):
    lookup_field = 'pk'
    serializer_class = ProductSerializer

    def get_queryset(self):
        qs = Product.objects.all()
        query = self.request.GET.get('q')
        if query is not None:
            qs = qs.filter(
                Q(title__icontains=query) |
                Q(description__icontains=query)
            ).distinct()
        return qs
Run Code Online (Sandbox Code Playgroud)

它的序列化器类:

class ProductRatingSerializer(ModelSerializer):
    class Meta:
        model = Product_ratings
        fields = [
            'p_id',
            'commenter',
            'comment',
            'rating',
            'created_date',
        ]
        read_only_fields = ['p_id']


class ProductSerializer(ModelSerializer):
    product_ratings = ProductRatingSerializer(many=True)
    author = serializers.SerializerMethodField()

    def get_author(self, obj):
        return obj.author.first_name
    class Meta:
        model = Product
        fields = [
            'product_id',
            'author',
            'category',
            'title',
            'description',
            'filepath',
            'price',
            'created_date',
            'updated_date',
            'product_ratings',
        ]
        read_only_fields = ['product_id', 'created_date', 'updated_date', 'author']
Run Code Online (Sandbox Code Playgroud)

相关型号类别:

class Product(models.Model):
    product_id = models.AutoField(primary_key=True)
    author = models.ForeignKey(User, on_delete=models.CASCADE, db_index=True)
    category = models.ForeignKey(Category, on_delete=models.CASCADE, to_field='cat_id')
    title = models.CharField(max_length=120)
    description = models.TextField(null=True, blank=True)
    price = models.CharField(max_length=50, null=True, blank=True)
    filepath = models.CharField(max_length=100, null=True, blank=True)
    created_date = models.DateTimeField(auto_now_add=True)
    updated_date = models.DateTimeField(auto_now=True)

class Product_ratings(models.Model):
    p_id = models.ForeignKey(Product, on_delete=models.CASCADE, to_field='product_id')
    commenter = models.ForeignKey(User, on_delete=models.CASCADE)
    comment = models.CharField(max_length=200, null=True, blank=True)
    rating = models.IntegerField(null=True, blank=True)
    created_date = models.DateTimeField(auto_now_add=True)
Run Code Online (Sandbox Code Playgroud)

nev*_*ner 9

ForeignKey 的默认反向查找名称是<mode>_setproduct_ratings_set在您的情况下,因此您需要将product_ratings字段 in替换ProductSerializerproduct_ratings_set

class ProductSerializer(ModelSerializer):
    product_ratings_set = ProductRatingSerializer(many=True)
    ...
    class Meta:
        model = Product
        fields = [
        ...
        'product_ratings_set'
        ]    
Run Code Online (Sandbox Code Playgroud)

您也可以将related_name='product_ratings'属性添加到模型的 ForeignKey 以更改反向查找名称,在这种情况下,您不需要太更改序列化程序:

class Product_ratings(models.Model):
    p_id = models.ForeignKey(Product, on_delete=models.CASCADE, to_field='product_id', related_name='product_ratings')
Run Code Online (Sandbox Code Playgroud)

  • 谢谢。我添加了一个像您所示的字段,但有错误。然而第二个解决方案是好的。:) (2认同)

小智 7

当我将没有Many=True 的查询集传递给序列化器对象时,出现此错误

qs = SomeObject.objects.all()
srz = SomeObjectSerializer(instance=qs)
srz.data # error happens here

# correct 1
qs = SomeObject.objects.all()
srz = SomeObjectSerializer(qs, many=True)
srz.data

# correct 2
qs = SomeObject.objects.filter(id=some_id).first()
srz = SomeObjectSerializer(qs)
srz.data
Run Code Online (Sandbox Code Playgroud)

一般提示:

-如果 Many=False (默认),则必须在序列化器中传递一个对象作为实例参数

-或者如果您传递查询集,您还必须将 Many=True 传递给序列化器


Zoh*_*Ali 5

就我而言,我必须从我的中仅返回单个对象,views.py但我正在返回queryset,因此更改objects.filterobjects.get我解决了问题