Django休息ModelViewSet序列化器创建失败

时间:2018-01-04 13:31:49

标签: django django-rest-framework django-rest-viewsets

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

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

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

并删除&#34; which_library&#34;但两个都给我错误:

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

我做错了什么?

1 个答案:

答案 0 :(得分:1)

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

  

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

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