【问题标题】:Django: Add record to the database table if it is not present alreadyDjango:如果记录不存在,则将记录添加到数据库表
【发布时间】:2020-03-25 13:15:52
【问题描述】:

我正在学习 Django Rest 框架。我一直在做一个小项目,我正在研究 4 个模型(数据库表)。这些模型是 1. Game 2. GameCategory 3. Player 4. PlayerScore。

Game 表有 5 列,其中 category 是链接表 Game 和 GameCategory 的外键。以下是 API 的 JSON 负载。

"url": "http://127.0.0.1:8000/games/3/",
"category": "Shooting",
"name": "PUB G",
"release_date": "2016-11-29",
"played": true

GameCategory 表有一个列名。

我当前的代码是这样一种方式,如果我将记录插入到表 Game 中,并且表中不存在 GameCategory 表中的类别,我将收到以下错误消息。

"category": [
        "Object with name=ABC does not exist."
    ]

但我希望它以某种方式提供,当游戏数据与 GameCategory 中不存在的类别的值一起提供时,该类别应自动添加到 GameCategory 表中,

对不起,如果这是一个太基本的问题。我到处搜索都找不到答案,我也支持这个框架,也支持 Web 开发。提前致谢!

【问题讨论】:

    标签: django django-models django-rest-framework django-serializer


    【解决方案1】:

    您可以使用get_or_createupdate_or_create 来帮助处理这种情况。

    instance, created = Model.objects.get_or_create(
        foo='bar',
        defaults={'spam': 'eggs'},
    )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-09-22
      • 1970-01-01
      • 2020-05-23
      • 1970-01-01
      • 1970-01-01
      • 2021-09-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多