当我要在邮递员中发布对象时,我得到了这个错误。
NULL约束失败: product_product.author_id
我在“授权”部分中包含了Basic Auth,无论如何,它会给我带来错误。
models.py
class Product(models.Model):
category = models.ForeignKey(Category, on_delete=models.CASCADE)
name = models.CharField(max_length=200)
brand = models.CharField(max_length=200)
rating = models.PositiveSmallIntegerField(default=0)
description = models.TextField()
author = models.ForeignKey(User, on_delete=models.CASCADE)serializers.py
class ProductSerializer(serializers.HyperlinkedModelSerializer):
category = serializers.SlugRelatedField(queryset=Category.objects.all(), slug_field='name')
author = serializers.ReadOnlyField(source='author.username')
class Meta:
model = Product
fields = ['id', 'url', 'category', 'name', 'brand', 'rating', 'description', 'price']为什么不发生零约束呢?我怎么才能解决这个问题?提前感谢!
发布于 2020-10-25 00:04:15
我认为您应该在models.create_all()中添加Models.py来创建数据库
发布于 2020-10-25 13:26:56
发生此错误的原因很简单,因为您的创建请求没有为产品的author属性提供值。
# models.py
class Product(models.Model):
....
author = models.ForeignKey(User, on_delete=models.CASCADE)所以要解决这个问题完全取决于你的业务逻辑,
- **[NO]** ==> then just make the foreign key `null=True, blank=True`
- **[YES]** ==> Then you need to modify your creation logic a lil bit.- **[YES]**, then this can easily be done by overriding your serializer's create method .... # Inside you serializer def create(self, validated\_data): validated\_data['author'] = self.context['request'].user return super().create(validated\_data)- **[NO]**, You have to make the serializer accept writes on `author` field.一个小注释,您的
ProductSerializer元类的字段属性,不包括'author',确保它也是在那里添加的。
https://stackoverflow.com/questions/57327623
复制相似问题