Django REST Framework NOT NULL约束失败 [英] Django REST Framework NOT NULL constraint failed

查看:51
本文介绍了Django REST Framework NOT NULL约束失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试通过发布以下JSON创建新帖子时:

when I try to create a new Post by posting the following JSON:

{
    "text": "test",
     "location": 1
}

我收到以下错误:

NOT NULL constraint failed: grapevineapp_post.location_id

models.py:

models.py:

class Location(models.Model):
    name = models.CharField(max_length=80)
    created = models.DateTimeField(auto_now_add=True)
    def __str__(self):
        return self.name

class Post(models.Model):
    text = models.CharField(max_length=512)
    owner = models.ForeignKey('auth.User', related_name='posts', on_delete=models.CASCADE)
    location = models.ForeignKey(Location, related_name='posts', on_delete=models.CASCADE)
    created = models.DateTimeField(auto_now_add=True)
    def __str__(self):
        return self.text

views.py:

class PostList(generics.ListCreateAPIView):
    permission_classes = (permissions.IsAuthenticatedOrReadOnly,)
    queryset = Post.objects.all()
    serializer_class = PostSerializer
    def perform_create(self, serializer):
        serializer.save(owner=self.request.user)

class PostDetail(generics.RetrieveUpdateDestroyAPIView):
    permission_classes = (permissions.IsAuthenticatedOrReadOnly,)
    queryset = Post.objects.all()
    serializer_class = PostSerializer

Serializers.py

Serializers.py

class PostSerializer(serializers.Serializer):
    id = serializers.IntegerField(read_only=True)
    text = serializers.CharField(required=False, allow_blank=True, max_length=512)
    owner = serializers.ReadOnlyField(source='owner.username')
    location = serializers.PrimaryKeyRelatedField(many=False, read_only=True)

    def create(self, validated_data):
        return Post.objects.create(**validated_data)

    def update(self, instance, validated_data):
        instance.text = validated_data.get('text', instance.text)
        instance.location = validated_data.get('location', instance.location)
        instance.save()
        return instance
class UserSerializer(serializers.ModelSerializer):
    posts = serializers.PrimaryKeyRelatedField(many=True, queryset=Post.objects.all())

    class Meta:
        model = User
        fields = ('id', 'username', 'posts')

DB已被清除.位置是使用管理界面创建的.我知道这个问题有些琐碎,但我无法解决.

DB has already been cleared. Locations have been created by using the admin interface. I know that the issue is something trivial, but I just can't get it to work.

推荐答案

要详细说明Willem Van Onsem所说的内容,请将您的 PostSerializer.location 字段设置为只读.您为其提供的json数据将被忽略(文档),即它不会包含在您的 validated_data 中.

To elaborate on what Willem Van Onsem said, you have your PostSerializer.location field set as read-only. The json data that you provided for it will be ignored (documentation), i.e. it won't be included in your validated_data.

然后,当您在 create 方法中调用 Post.objects.create(** validated_data)时,它将尝试创建 Post 的实例没有location参数,您会收到错误消息.

Then when you call Post.objects.create(**validated_data) in your create method it tries to create an instance of Post without the location argument and you get your error.

在上面关于queryset的评论之后.

After your comment above about queryset.

您需要为其提供一个查询集,以针对(文档).根据您的情况

You need to provide a queryset for it to validate against (documentation). In your case you want

location = serializers.PrimaryKeyRelatedField(
    many=False,
    queryset=Location.objects.all()
)

这篇关于Django REST Framework NOT NULL约束失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆