Django休息嵌套序列化器失败

时间:2018-01-01 19:41:11

标签: django django-rest-framework

我的模特关系是:'读者'将有一个'愿望清单',而'愿望清单'将包含许多'预订'。我想在Reader对象实例创建过程中自动创建一个空的愿望清单。

我的模特:

class Wishlist(models.Model):
    wishlist_id = models.AutoField(primary_key=True)        


class Reader(models.Model):
    user = models.OneToOneField(User)
    phone = models.CharField(max_length=30)
    address = models.CharField(max_length=80)
    dob = models.DateField(auto_now=False, auto_now_add=False, null=True, blank=True)
    # A library has many readers
    which_library = models.ForeignKey('Library', related_name='readers', on_delete=models.CASCADE)
    wishlist = models.OneToOneField(Wishlist, null=True, blank=True)


class Book(models.Model):
    book_id = models.AutoField(primary_key=True)
    title = models.CharField(max_length=30)
    which_wishlist = models.ForeignKey('Wishlist', related_name='my_wishlist', on_delete=models.CASCADE, null=True, blank=True)

序列化器:

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', 'wishlist')

    def update(self, instance, validated_data):
        instance.user.email = validated_data.get('user.email', instance.user.email)
        instance.user.password = validated_data.get('user.password', instance.user.password)
        instance.phone = validated_data.get('phone', instance.phone)
        instance.address = validated_data.get('address', instance.address)
        instance.dob = validated_data.get('dob', instance.dob)
        instance.which_library = validated_data.get('which_library', instance.which_library)
        instance.wishlist = validated_data.get('wishlist', instance.wishlist)
        instance.save()
        return instance

    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()
        wishlist_data = validated_data.pop('wishlist')
        reader = Reader.objects.create(**validated_data)
        Wishlist.objects.create(reader=reader, **wishlist_data)
        return reader

我处理创作的视图:

@api_view(['GET', 'POST'])
def reader(request, library_id):
    """
    List all readers in a specific library, or create a new

    """
    if request.method == 'GET':
        ...

    elif request.method == 'POST':
        serializer = ReaderSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        else:
            return Response(
                serializer.errors, status=status.HTTP_400_BAD_REQUEST)

我正在进行POST调用以创建一个包含以下JSON数据的Reader:

{
    "username": "sample",
    "email": "sample@gmail.com",
    "password": "012345",
    "phone": "012345",
    "address": "sample address",
    "which_library": "2",
    "wishlist": []
}

它给了我以下错误:

{
    "wishlist": [
        "Incorrect type. Expected pk value, received list."
    ]
}

我做错了什么?

1 个答案:

答案 0 :(得分:2)

我会完全抛弃Wishlist模型,因为它没有任何数据。

class Book(models.Model):
    book_id = models.AutoField(primary_key=True)
    title = models.CharField(max_length=30)
    reader = models.ManyToManyField('Reader', related_name='wishlist')

由于您不再需要自动创建心愿单,这应该会让整个事情变得更容易,我想您的问题将在空中解决。

如果您需要该模型(例如,您希望以后出现数据),可以在through上使用ManyToManyField。可以找到详细信息in the docs

<强>更新

我重新考虑了关于直通模型的建议。这种方法不会反映您当前的状态,因为每个关系不会有一个条目,而不是每个读者。不过,我建议按照上面的建议简化模型。