Not Null constrained error on field handled in views.py

后端 未结 1 2089
广开言路
广开言路 2020-12-22 07:06

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 = model         


        
相关标签:
1条回答
  • 2020-12-22 07:28

    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.

    class ReviewSerializer(serializers.ModelSerializer):
        author = UserSerializer(read_only=True)
        class Meta:
            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?

    0 讨论(0)
提交回复
热议问题