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 obtuvo AttributeError al intentar obtener un valor para el campo

Quiero obtener todos los valores de la tabla prodcut con la tabla de clasificación de productos. Hice algo como esto, pero este código me da AttributeError . Así que hice product_ratings = ProductRatingSerializer(many=True) en el serializador de productos y usé este valor en el campo, pero no funciona:

El mensaje de error completo:

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

vista :

 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

sus clases de serializador:

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

clase de modelo relacionado:

 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

El nombre de búsqueda inversa predeterminado para ForeignKey es <mode>_set o product_ratings_set en su caso, por lo que debe reemplazar el campo product_ratings en ProductSerializer con product_ratings_set :

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

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

También puede agregar related_name='product_ratings' a la ForeignKey del modelo para cambiar el nombre de búsqueda inversa, en este caso no necesita cambiar demasiado el serializador:

 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

en mi caso, tuve que devolver solo un objeto de mis views.py pero estaba devolviendo queryset , por lo que cambiar objects.filter a objects.get me solucionó el problema

over 4 years ago · Santiago Trujillo Report

0

La respuesta seleccionada no me funciona. Sin embargo, la siguiente manera funcionó:

 product_ratings = ProductRatingSerializer(many=True)

También recuerde poner product_ratings en el campo related_name de esta manera:

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

Así es como se ve la clase Meta:

 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!