【问题标题】:django-rest-framework: how do I update a nested foreign key? My update method is not even calleddjango-rest-framework:如何更新嵌套的外键?我的更新方法甚至没有被调用
【发布时间】:2022-01-22 02:43:18
【问题描述】:

我有这样的东西(我只包括了相关部分):

class ImageSerializer(serializers.ModelSerializer):
  telescopes = TelescopeSerializer(many=True)

  def update(self, instance, validated_data):
    # In this method I would perform the update of the telescopes if needed.
    # The following line is not executed.
    return super().update(instance, validated_data)

  class Meta:
    model = Image
    fields = ('title', 'telescopes',)

当我执行GET 时,我会得到我想要的嵌套数据,例如:

{
  'title': 'Some image',
  'telescopes': [
    'id': 1,
    'name': 'Foo'
  ]
}

现在,如果我想通过更改名称而不是望远镜来更新此图像,我会PUT 如下:

{
  'title': 'A new title',
  'telescopes': [
    'id': 1,
    'name': 'Foo'
  ]
}

似乎django-rest-framework 甚至没有调用我的update 方法,因为模型验证失败(Telescope.name 有一个unique 约束),而django-rest-framework 正在验证它,就好像它想创建它一样?

当我不使用嵌套序列化程序时,一切正常,而只是使用 PrimaryKeyRelatedField,但出于性能原因(以避免过多的 API 调用),我确实需要嵌套序列化程序。

有人知道我错过了什么吗?

谢谢!

【问题讨论】:

    标签: django django-rest-framework


    【解决方案1】:

    您将在此处找到您的解决方案 Django rest relations

    【讨论】:

      猜你喜欢
      • 2017-08-15
      • 2016-01-09
      • 2013-10-24
      • 2017-04-14
      • 2017-12-03
      • 1970-01-01
      • 2016-02-09
      • 2014-03-24
      • 1970-01-01
      相关资源
      最近更新 更多