Home > Enterprise >  django AttributeError when saving data with DRF
django AttributeError when saving data with DRF

Time:12-30

I have a problem when I make a POST. the entry is created (I can see it in django Admin panel) but DRF is throwing me an error

AttributeError at /api/v1/reviews/

'Review' object has no attribute 'review_score'

review_score beeing a SerializerMethodField in serializer.py needed for the frontend (GET is working perfectly)

model.py

class Review(models.Model):
    company = models.ForeignKey(Company, related_name='company_review', on_delete=models.CASCADE)
    title = models.CharField(max_length=255)
    comments = models.TextField()
    validated = models.BooleanField(default=False)
    note_quality = models.DecimalField(max_digits=5, decimal_places=2)
    note_timing = models.DecimalField(max_digits=5, decimal_places=2)
    note_qualprix = models.DecimalField(max_digits=5, decimal_places=2)
    note_react = models.DecimalField(max_digits=5, decimal_places=2)
    note_followup = models.DecimalField(max_digits=5, decimal_places=2)
    note_clean = models.DecimalField(max_digits=5, decimal_places=2)

    created_at = models.DateField(auto_now_add=True)
    created_by = models.ForeignKey(User, related_name='created_review', on_delete=models.CASCADE)

    def __str__(self):
        return self.title

views.py

class ReviewViewSet(viewsets.ModelViewSet):
    serializer_class = ReviewSerializer
    queryset = Review.objects.all()

    def get_queryset(self):
        company_id = self.request.query_params.get('company_id', None)

        return self.queryset.filter(company_id=company_id, validated=True).annotate(
            review_score = Sum(F('note_quality') F('note_timing') F('note_qualprix') F('note_react') F('note_followup') F('note_clean'))/6,
        )

    def perform_create(self, serializer):
        obj = serializer.save(created_by=self.request.user)

serializer.py

class ReviewSerializer(serializers.ModelSerializer):
    created_by = UserCreateSerializer(read_only=True)
    review_score = serializers.SerializerMethodField()

    def get_review_score(self, obj):
        rounded = round_up(obj.review_score, 0.5)        
        return rounded

    class Meta:
        model = Review
        read_only_fields = ('created_at'),
        fields = ('id','company','title','comments','validated','note_quality','note_timing','note_qualprix','note_react','note_followup','note_clean','created_at', 'created_by', 'review_score')

CodePudding user response:

review_score at ReviewSerializer should be a serializers.ReadOnlyField(). Change that and it should work.

CodePudding user response:

You should remove row

obj.save()

in the perform_create function. Model saving is already happening in the line

obj = serializer.save(created_by=self.request.user)
  • Related