【发布时间】:2015-11-13 09:10:38
【问题描述】:
在 drf3 中,您现在可以通过重写 create() 方法并自己处理 valid_data 来实现可写的嵌套序列化程序。但是,如果您在模型中有这样的多层嵌套关系怎么办:
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'
)
如何使用自定义创建方法为订单编写序列化程序来处理这种情况?我见过的所有例子,包括官方页面上的例子,都只有一层嵌套关系。
Read 与 depth 参数一起工作正常。不过,我真的 感谢您对编写创建/更新方法的任何帮助。
【问题讨论】:
标签: django django-rest-framework