我正在学习Django Rest Framework。我一直在一个小项目中,我正在研究4个模型(数据库表)。这些模型是1.游戏2.游戏类别3.玩家4.玩家分数。
表[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具有一个列名。
我当前的代码是这样的,如果我将记录插入表GameCategory中不存在的类别的游戏表中,则会收到以下错误消息。
"category": [
"Object with name=ABC does not exist."
]
但是我希望这样,当为游戏数据提供GameCategory中不存在的类别的值时,应将该类别自动添加到GameCategory表中,
抱歉,这是一个太基本的问题。我到处搜索都找不到答案,而且我也希望这个框架也适用于Web开发。预先感谢。!
您可以使用get_or_create
或get_or_create
来帮助解决这种情况。
update_or_create