【问题标题】:DRF3 M2M nested serializer removing nested 'id' fields on update()DRF3 M2M 嵌套序列化程序删除 update() 上的嵌套“id”字段
【发布时间】:2015-03-17 20:37:41
【问题描述】:

我正在尝试创建一个功能齐全的 M2M(通过表)嵌套序列化程序,它在 create() 上完美运行。但是,当我获取包含嵌套记录的 id 的序列化程序的 GET 版本返回的 JSON 并针对同一个序列化程序执行 PUT 时,“id”字段在它到达时从嵌套记录 valid_data 中删除update() 方法。

{
"id": 1, 
"addresses": [
    {
        "id": 1,  # This is ripped out
        "city": "Oakville", 
        "addr": "13 Main St", 
        "postal_code": "01101"
    }, 
    {
        "id": 2,  # This is ripped out
        "city": "Watertown", 
        "addr": "88 Main St", 
        "postal_code": "01101"
    }, 
    "customer_number": 1234, 
    "customer_type": 1, 
    "pricing_sequence": 2, 
    "name": "Customer number 1234"
 }

有什么想法吗?

【问题讨论】:

  • 在某处有一个副本,但答案是这是 AutoField 的预期行为。
  • 那么给定一个嵌套的 M2M 序列化程序,是否无法编写更新嵌套项的更新方法,因为 update() 方法不知道要更新的相关记录的“id”?这使得 PUT/PATCH 变得毫无价值。

标签: python django django-rest-framework


【解决方案1】:

是的,这是 django-rest-framework: serializer from DATA don't update model ID 的副本

我想我明白了。默认情况下,ModelSerializer 似乎将“id”字段设为只读。解决方案是向序列化程序添加一个显式的“id”字段。见tomchristie的评论https://github.com/tomchristie/django-rest-framework/issues/2114

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-10-26
    • 1970-01-01
    • 2019-05-11
    • 1970-01-01
    • 1970-01-01
    • 2016-02-13
    • 1970-01-01
    相关资源
    最近更新 更多