[Fixed]-Django-rest-framwork got AttributeError when attempting to get a value for field

19👍

Default reverse lookup name for ForeignKey is <mode>_set or product_ratings_set in your case, so you need to replace product_ratings field in ProductSerializer with product_ratings_set:

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

Also you can add related_name='product_ratings' attribute to model’s ForeignKey to change reverse lookup name, in this case you don’t need too change serializer:

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

7👍

I got this error when I had passed the queryset without many=True to the serializer object

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

general tip:

-if many=False (default) you must pass an object for instance argument in Serializer

-or if you pass a queryset you must also pass many=True to Serializer

5👍

in my case I had to return just single object from my views.py but I was returning queryset, so changing objects.filter to objects.get fixed the issue for me

3👍

Selected answer doesn’t work for me. However following way worked:

product_ratings = ProductRatingSerializer(many=True)

Also remember to put product_ratings in related_name field like this:

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

Here is how Meta class looks:

class Meta:
        model = Product
        fields = [
        ...
        'product_ratings'
        ]  
👤sAm

Leave a comment