Django rest ModelViewSet 序列化程序创建失败

Django rest ModelViewSet serializer create fails

我有两个模型具有以下关系:

class Library(models.Model):
    library_id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=30)
    ...

class Reader(models.Model):
    user = models.OneToOneField(User)
    phone = models.CharField(max_length=30)
    ...
    # A library has many readers
    which_library = models.ForeignKey('Library', related_name='readers', on_delete=models.CASCADE)

我定义了序列化程序如下(我在为特定库创建 Reader 时直接创建用户):

class ReaderSerializer(serializers.ModelSerializer):
    username = serializers.CharField(source='user.username')
    email = serializers.CharField(source='user.email')
    password = serializers.CharField(source='user.password')

    class Meta:
        model = Reader
        #fields = '__all__'
        depth = 1
        fields = ('id', 'username', 'email', 'password', 'phone', 'address', 'dob', 'which_library')


    def create(self, validated_data):
        user_data = validated_data.pop('user')
        user = User.objects.create(**user_data)
        user.set_password(user_data['password'])
        user.save()
        reader = Reader.objects.create(user=user, **validated_data)
        return reader

我正在编写一个 ModelViewSet,如下所示:

class ReaderViewSet(viewsets.ModelViewSet):

serializer_class = ReaderSerializer

def get_queryset(self):

    readers = Reader.objects.filter(which_library=self.kwargs.get('library_id'))
    return readers

URL: router.register(r'readers/(?P<library_id>[0-9]+)', ReaderViewSet, base_name='readers')

我的 GET 调用成功,我获得了特定图书馆中的所有读者。

我正在使用以下 JSON 数据进行 POST 调用:

{
    "username": "three",
    "email": "three@gmail.com",
    "password": "5647",
    "phone": "836365",
    "address": "sample6 address",
    "which_library": "2"
}

也通过删除 "which_library" 但都给我错误:

IntegrityError at /api/readers/2/
(1048, "Column 'which_library_id' cannot be null")

我做错了什么?

尝试删除 depth = 1 选项。来自 docs:

The default ModelSerializer uses primary keys for relationships, but you can also easily generate nested representations using the depth option.

看起来这个选项序列化程序需要对象而不是 id。