Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

2.4K
Views
django-rest-framwork got AttributeError when attempting to get a value for field

I want to get all prodcut table values with join product_ratings table. I did somthing like this but this code give me AttributeError. So I did product_ratings = ProductRatingSerializer(many=True) in product serializer and used this value in the field, but it's not working:

The full error message:

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

view :

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

its serializer classes:

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

related model class :

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)
over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

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

 class ProductSerializer(ModelSerializer):
 product_ratings_set = ProductRatingSerializer(many=True)

 class Meta: 
 model = Product
 fields = [ ... 'product_ratings_set' ]

You can also add related_name='product_ratings' to the ForeignKey of the model to change the reverse lookup name, in this case you don't need to change the serializer too much:

 class Product_ratings(models.Model): p_id = models.ForeignKey(Product, on_delete=models.CASCADE, to_field='product_id', related_name='product_ratings')
over 4 years ago · Santiago Trujillo Report

0

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

over 4 years ago · Santiago Trujillo Report

0

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'
        ]  
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!