【问题标题】:django rest framework 3.1 Handle create/update in ModelSerializer where do i validate the nested data?django rest framework 3.1 在 ModelSerializer 中处理创建/更新我在哪里验证嵌套数据?
【发布时间】:2015-07-08 23:15:06
【问题描述】:

我尝试使用嵌套表示来创建和更新资源。

我看了一下这里 -> http://www.django-rest-framework.org/api-guide/serializers/#writable-nested-representations。但我不知道将验证放在哪里来验证我的嵌套资源(不是由其 id 定义的)是否存在。

json

{
    "name": "this is my name"
    "network": {
        "code": "existing_code",
        "operator": "existing_op"
    },
 }

我的序列化程序的创建方法

def create(self, validated_data):

    network = validated_data.pop("network")

    #this could throw a DoesNotExist exception !!!!
    validated_data["network"] = Network.objects.get(operator=network["operator"], code=network["code"])

    instance = manny.common.models.DeliveryPoint.objects.create(**validated_data)
    return instance

是否可以直接在 ModelSerializer 上的验证器中检查这个:

验证我的序列化程序的方法

def validate(self, data):
    #some code here....

    if not Network.objects.filter(operator=data["operator"], code=data["code"]).exists():
        raise serializers.ValidationError("network doesn't exist")
    return data

还是必须重写ModelViewSet的create方法?

感谢您的帮助!

【问题讨论】:

    标签: django-rest-framework


    【解决方案1】:

    为什么不使用get_object_or_404 (https://docs.djangoproject.com/fr/1.8/topics/http/shortcuts/#get-object-or-404) 而不是Network.objects.get

    如果 Network 对象不存在,则引发的异常会产生 404 错误,您无需手动处理。

    【讨论】:

    • 嗨,我认为视图无法正确处理序列化程序中抛出的 Http404 异常,但是...我错了,谢谢您的回复!
    猜你喜欢
    • 1970-01-01
    • 2016-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-08
    • 2020-07-11
    • 2015-02-10
    相关资源
    最近更新 更多