0

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

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)

我已经将序列化程序定义如下(我在为特定库创建阅读器时直接创建用户):

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

网址: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")

我究竟做错了什么?

4

1 回答 1

1

尝试删除depth = 1选项。从文档

默认的 ModelSerializer 使用主键来表示关系,但您也可以使用 depth 选项轻松生成嵌套表示。

看起来使用此选项序列化程序需要对象而不是 id。

于 2018-01-04T14:04:28.327 回答