本文介绍了在views.py中处理的字段上没有Null约束的错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用django rest框架。我有产品和评论模型。评论与产品相关,例如;

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=200, null=False, blank=False)
    description = models.TextField(max_length=2000, null=False, blank=False)
    owner = models.ForeignKey(User, on_delete=models.CASCADE)
    slug = models.SlugField(unique=True)
    category = models.ForeignKey(Category, on_delete=models.CASCADE)
    is_featured = models.BooleanField(default=False)
    created= models.DateTimeField(auto_now_add=True)

class Review(models.Model):
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    product= models.ForeignKey(Product, on_delete=models.CASCADE)
    title = models.CharField(max_length=80, blank=False, null=False)
    body = models.TextField(max_length=400, blank=False, null=False)
    is_approved = models.BooleanField(default=False)
    created = models.DateTimeField(auto_now_add=True)

我为评论编写了一个序列化器类:

I wrote a serializer class for the review:

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
        review = Review.objects.create(title=title, body=body, author=author)
        return review

,在我的views.py中,我有这个;

and in my views.py, i have this;

class ReviewCreateView(CreateAPIView):
    serializer_class = ReviewSerializer
    queryset = Review.objects.all()
    permission_classes = [IsAuthenticated,]
    authentication_classes = [TokenAuthentication,]

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        product_id = kwargs.get('product')
        product = Product.objects.get(id=product_id)
        serializer.save(product=product)
        headers = self.get_success_headers(serializer.data)
        return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)

在我的网址urlpatterns中:

in my urls urlpatterns:

path('api/review/new/<product>/', ReviewCreateView.as_view(), name="create-review"),

问题是,当我从前端向该api发送评论时,我不断收到Not Null约束错误,如下所示:$ api $ b IntegrityError at / api / review / new / 23 / NOT NULL约束失败:products_review.product_id

Issue is when i send a review from the frontend to that api, i keep getting a Not Null constraint error like so:IntegrityError at /api/review/new/23/ NOT NULL constraint failed: products_review.product_id

我已经在视图中处理了CreateAPIView中的产品保存,但是由于某些原因,Django是采摘它。请问我该如何进行这项工作?任何帮助将不胜感激。请注意,我在这里找到的类似问题的答案对我不起作用。

I have handled the product saving inside the CreateAPIView in my views, but for some reasons Django isn't picking it. How do i make this work please? Any assistance will be appreciated. Please note that answers for similar questions i found here didn't work for me.

推荐答案

您几乎是正确的。您传递了产品实例,因此应将其包含在 ReviewSerializer.create 方法的validated_data中。但是,在实际创建审阅实例时,不会使用它。

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

为什么您不能只在您的评论序列化器上有一个产品字段?

Also why can't you just have a product field on your review serializer?

这篇关于在views.py中处理的字段上没有Null约束的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-25 07:56