在django休息框架中实现多级嵌套关系的可写串行器 [英] Implement a writable serializer for multilevel nested relationships in django rest framework

查看:121
本文介绍了在django休息框架中实现多级嵌套关系的可写串行器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在drf3中,您现在可以通过覆盖create()方法并自己处理validated_data来实现可写入的嵌套序列化。但是,如果您在模型中有多层次的嵌套关系,如下所示:

In drf3 you can now implement a writable nested serializer by overriding the create() method and handling validated_data yourself. However, what if you've a multi-level nested relationship in the models like so:

class Order(models.Model):
    """
    Order model to aggregate all the shipments created by a user at a particular time.
    """
    created_at = models.DateTimeField(
        verbose_name='created at',
        auto_now_add=True
    )
    updated_at = models.DateTimeField(
        verbose_name='updated at',
        auto_now=True
    )

class Shipment(models.Model):
    """
    Many to One Relationship with the Orders Model. Aggregates all the details of a shipment being sent.
    """
    created_at = models.DateTimeField(
        verbose_name='created at',
        auto_now_add=True
    )
    updated_at = models.DateTimeField(
        verbose_name='updated at',
        auto_now=True
    )
    order = models.ForeignKey(
        to=Order
    )

class ItemDetail(models.Model):
    """
    Specifies details of the shipment contents. One to One relationship with the Shipment Model.
    """
    shipment = models.OneToOneField(
        to=Shipment,
        primary_key=True
    )
    CONTENT_TYPES = (
        ('D', 'Documents'),
        ('P', 'Products')
    )
    content = models.CharField(
        verbose_name='package contents',
        max_length=1,
        choices=CONTENT_TYPES,
        default='P'
    )

如何使用自定义创建方法编写序列化程序来处理这种情况?我所看到的所有示例包括官方页面上的一个例子只有一个层次的嵌套关系。

How would I write a serializer for order with custom create method to handle such a case? All the examples I've seen including the one on the official page has just one level of nested relationship.


阅读在深度参数中工作正常,但是我真的非常感谢任何帮助编写创建/更新方法。 p>

Read is working fine with the depth argument. However, I'd really appreciate any help with writing the create/update method.


推荐答案

可写嵌套序列化器在文档中解释

请不要在创建/更新中重新创建一个新的序列化程序。
一旦你打了最大的序列化器创建/更新,你的所有数据都被验证,包括嵌套的数据。

Please do not recreate a new serializer in the create/update. Once you hit the top most serializer create/update, all your data are validated, including the nested ones.

在这一点上,你必须自己编写从validated_data到各种对象的映射。

At this point, you'll have to write by yourself the mapping from the validated_data to your various objects.

我试图使它自动为DRF 2.x,但事实证明,使用情况太多,其中一些是排他性的。因此,DRF让开发人员工作 - 即你。

I tried to make it automatic for DRF 2.x but it turns out that there was too many use case, some of which were exclusives. Therefore DRF leaves that work upon the developer - i.e. you.

这篇关于在django休息框架中实现多级嵌套关系的可写串行器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆