Django REST Framework NOT NULL约束失败

时间:2018-12-08 21:17:08

标签: python django django-rest-framework

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

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

我收到以下错误:

NOT NULL constraint failed: grapevineapp_post.location_id

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

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已被清除。位置是使用管理界面创建的。我知道这个问题很琐碎,但我无法解决。

1 个答案:

答案 0 :(得分:0)

要详细说明Willem Van Onsem所说的内容,您将PostSerializer.location字段设置为read-only。您为其提供的json数据将被忽略(documentation),即不会包含在您的validated_data中。

然后,当您在Post.objects.create(**validated_data)方法中调用create时,它将尝试创建不带location参数的Post实例,并且会出现错误。

编辑:在上面关于queryset的评论之后。

您需要为其提供一个查询集以针对(documentation)进行验证。根据您的情况

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