使用POST创建新记录会出现错误:调用Product.objects.create()时出现TypeError

时间:2018-02-22 07:47:45

标签: python django django-rest-framework

我正在使用Django REST Framework并拥有以下视图类来查看或创建产品。现在我尝试使用POST方法添加新记录,但我收到以下错误。任何人都可以告诉我为什么以及如何解决这个问题?

已更新。

TypeError at /store/view/
Got a `TypeError` when calling `Product.objects.create()`. This may be because you have a writable field on the serializer class that is not a valid argument to `Product.objects.create()`. You may need to make the field read-only, or override the ProductSerializer.create() method to handle this correctly.

查看课程:

class StoreApiView(mixins.CreateModelMixin, generics.ListAPIView):
    lookup_field = 'pk'
    serializer_class = ProductSerializer
    permission_classes = [IsAuthenticatedOrReadOnly]

    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

    def perform_create(self, serializer):
        serializer.save(author=self.request.user, context={'request': self.request})

    def post(self, request, *args, **kwargs):
        return self.create(request, *args, **kwargs)

和相关的序列化程序类:

class ProductSerializer(ModelSerializer):
    product_ratings = ProductRatingSerializer(many=True, read_only=True)
    product_badges_set = ProductBadgesSerializer(many=True, read_only=True)

    author = serializers.SerializerMethodField()

    def get_author(self, obj):
        return obj.author.first_name + ' ' + obj.author.last_name

    def get_category(self, obj):
        return obj.category.title

    class Meta:
        model = Product
        fields = [
            'product_id',
            'author',
            'title',
            'mini_description',
            'you_learn',
            'you_need',
            'full_description',
            'price',
            'video_level',
            'video_length',
            'created_date',
            'updated_date',
            'product_ratings',
            'product_badges_set',
        ]
        read_only_fields = ['product_id', 'created_date', 'updated_date', 'author','product_badges_set',
                            'product_ratings']

模型:

class Product(models.Model):
    product_id = models.AutoField(primary_key=True)
    author = models.ForeignKey(User, on_delete=models.CASCADE, db_index=True)
    title = models.CharField(max_length=120)
    video_length = models.CharField(max_length=20, null=True, blank=True)
    mini_description = models.CharField(max_length=220, null=True, blank=True)
    full_description = models.TextField(null=True, blank=True)
    you_need = models.CharField(max_length=120, null=True)
    you_learn = models.CharField(max_length=250, null=True)
    price = models.CharField(max_length=50, null=True, blank=True)
    video_level = models.CharField(max_length=100, null=True, blank=True)
    created_date = models.DateTimeField(auto_now_add=True)
    updated_date = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.title

    @property
    def owner(self):
        return self.author

1 个答案:

答案 0 :(得分:0)

对于有类似问题的人来说,这个问题指的是在我的代码中传递请求,我根据cezar的评论用下面的代码替换它。

serializer.save(作者= self.request.user)

三江源