Not Null Constrained Error On Field Handled In Views.py
I am working with django rest framework. I have Product and Review models. Review is related to Product like so; class Product(models.Model): name = models.CharField(max_length
Solution 1:
You are almost right. You passed the product instance, so it should be included in the validated_data for the ReviewSerializer.create
method. But you don't use it when you are actually creating the review instance.
classReviewSerializer(serializers.ModelSerializer):
author = UserSerializer(read_only=True)
classMeta:
model = Review
fields = ['id', 'author', 'title', 'body', 'is_approved', 'created']
def create(self, validated_data):
title = validated_data.get('title')
body = validated_data.get('body')
author = self.context['request'].user
product = validated_data.get('product')
review = Review.objects.create(
title=title,
body=body,
author=author,
product=product
)
return review
https://www.django-rest-framework.org/api-guide/serializers/#passing-additional-attributes-to-save
Also why can't you just have a product field on your review serializer?
Post a Comment for "Not Null Constrained Error On Field Handled In Views.py"