django-rest-framwork Got AttributeError when attempting to get a value for field
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'
]
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')
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