Django REST:在POST中通过slugs传递对象,但是通过id反序列化

时间:2014-01-23 23:06:09

标签: django django-models django-rest-framework

我一直在努力解决这个问题(对于Django Rest Framework而言是新手)。

给出示例模型

class BigModel(models.Model):
    id = models.AutoField(primary_key=True)
    something = models.CharField()
    nested = models.ForeignKey(SmallModel)

class SmallModel(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField()

我基本上想要传递以下JSON

{"something": "whatever", "nested": "existing name" }

会在给定字符串中查找SmallModel,并在反序列化后在nested_id上设置正确的BigModel

我知道这部分是SlugRelatedField的用途,但是我没有运气。

我目前对序列化程序的攻击如下(我基本上是手动查找):

class BigModelSerializer(serializers.ModelSerializer):
    nested = serializers.RelatedField()

    def validate(self, attrs):
        attrs['nested'] = SmallModel.objects.get(id=attrs['nested'])

    def validate_nested(self, attrs, source):
        nestedName = attrs[source]
        if SmallModel.objects.get(name=nestedName) is None:
            # Error
        nestedId = Stage.objects.get(name=nestedName).id
        attrs[source] = nestedId
        return attrs

    class Meta:
        model = BigModel
        fields = ('nested', 'something')

有了这个,我收到了这个错误:

argument of type 'NoneType' is not iterable

这基本上意味着is_valid()在序列化程序上失败。

如果nested上的BigModelSerializer字段设置为PrimaryKeyRelatedField,则验证甚至不会被调用...

0 个答案:

没有答案