django-rest-framwork在尝试获取字段值时遇到AttributeError

时间:2018-02-10 10:34:25

标签: python django django-rest-framework

我希望通过join product_ratings表获取所有prodcut表值。我做了这样的事情,但这段代码给了我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'.

观点:

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

其序列化程序类:

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']

相关模型类:

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)

2 个答案:

答案 0 :(得分:0)

在您的情况下,ForeignKey的默认反向查找名称为<mode>_setproduct_ratings_set,因此您需要将product_ratings中的ProductSerializer字段替换为product_ratings_set:< / p>

class ProductSerializer(ModelSerializer):
    product_ratings_set = ProductRatingSerializer(many=True)
    ...
    class Meta:
        model = Product
        fields = [
        ...
        'product_ratings_set'
        ]    

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

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

答案 1 :(得分:0)

在我的情况下,我只能从我的views.py返回一个对象,但是我正在返回queryset,因此将objects.filter更改为objects.get可以解决我的问题