【发布时间】:2015-10-23 08:35:14
【问题描述】:
我正在使用 Django Rest Framework 来创建一个对象。 JSON 也包含嵌套对象;要创建并链接到“主对象”的对象数组以及应部分更新的对象。
JSON 看起来像这样:
{
"opcitem_set" : [
{
"comment" : "Test comment",
"grade" : "1",
"name" : "1a"
},
{
"comment" : "Test comment",
"grade" : "2",
"name" : "1b"
},
{
"description" : "Additional test item",
"comment" : "Additional comment",
"grade" : "1",
"name" : "extra_1"
}
],
"is_right_seat_training" : false,
"checked_as" : "FC",
"date" : "2015-10-23",
"check_reason" : "Check ride",
"opc_program" : "2",
"is_pc" : true,
"questionnaire_test_passed" : "Passed",
"pnf_time" : 2,
"other_comments_complete_crew" : "Other comments",
"other_comments_flying_pilot" : "Other comments",
"is_cat_2_training" : false,
"opc_passed" : "Passed",
"pilot" : {
"pc_valid_to" : "2015-10-23",
"id" : 721,
"email" : "jens.nilsson@nextjet.se",
"total_time" : 3120,
"medical_valid_to" : "2015-10-23"
},
"pf_time" : 2,
"aircraft_type" : "S340",
"typeratingexaminer" : 734
}
“opcitem_set”包含类型为 OpcItem 的对象,这些对象应被创建并具有主对象的 ForeignKey。到目前为止一切顺利,我可以通过覆盖 ModelSerializer 上的 create() 方法来做到这一点,如 http://www.django-rest-framework.org/api-guide/serializers/#writable-nested-representations 中所述。
然后我们有“飞行员”对象的情况。这将始终包含一个 ID 和一些其他字段来修补具有该 ID 的对象。
“typeratingexaminer”字段只是另一个“Pilot”对象,但它不应该被修补,只是设置为外键。
我的问题是:我可以在 create() 方法中修补(部分更新)“试点”,还是会破坏某种设计模式?由于它实际上是 PATCH 而不是 POST,我应该在原始请求完成后在单独的请求中执行它吗?在这种情况下,我是否可以有一个跨越两个请求的事务,这样如果第二个请求失败,第一个请求将被回滚?
希望能够只从客户端发送一个请求,而不是将其拆分为两个请求。也许您可以将 ViewSet 中已经存在的 JSON 分离并发送到不同的序列化器?
很高兴听到您对此的看法,我有点迷茫。
【问题讨论】:
标签: python json django django-rest-framework