gpt4 book ai didi

mysql - Django:保存到数据库connundrun

转载 作者:行者123 更新时间:2023-11-29 01:51:53 30 4
gpt4 key购买 nike

我认为以下内容非常有效:

if request.method == 'POST':

form = SelectTwoTeams(request.POST,user=request.user)

if form.is_valid():

teamSelection1 = UserSelection(campaignno = 102501350,
teamselection1or2 = 1,
teamselectionid_id = request.POST['team1'],
user_id=currentUserID,
fixturematchday=fixturematchday,
soccerseason_id=soccerseason)
teamSelection1.save()

teamSelection2 = UserSelection(campaignno = 102501350,
teamselection1or2 = 2,
teamselectionid_id = request.POST['team2'],
user_id=currentUserID,
fixturematchday=fixturematchday,
soccerseason_id=soccerseason)
teamSelection2.save()

当代码运行时,它会在我的数据库中正常运行:

mysql> select * from straightred_userselection;
+-----------------+------------+-------------------+-----------------+---------+-----------------+----------------+
| userselectionid | campaignno | teamselection1or2 | teamselectionid | user_id | fixturematchday | soccerseasonid |
+-----------------+------------+-------------------+-----------------+---------+-----------------+----------------+
| 9 | 102501350 | 1 | 6 | 349 | 2 | 1025 |
| 10 | 102501350 | 2 | 7 | 349 | 2 | 1025 |
+-----------------+------------+-------------------+-----------------+---------+-----------------+----------------+
2 rows in set (0.00 sec)

但是,假设我现在想选择两个不同的团队(目前 teamselectionid 列下的 6 和 7)。我可以在我的表单中选择它们并更新但是当代码运行时它只是向表中添加另外两行而不是更新当前行。检查是否需要更新的一组新团队选择很简单:

  • fixturematchday 和 soccerseasonid 相同然后更新
  • fixturematchday 和 soccerseasonid 不同然后创建新条目

如上所述,它目前只添加了两个新行,如下所示:

mysql> select * from straightred_userselection;
+-----------------+------------+-------------------+-----------------+---------+-----------------+----------------+
| userselectionid | campaignno | teamselection1or2 | teamselectionid | user_id | fixturematchday | soccerseasonid |
+-----------------+------------+-------------------+-----------------+---------+-----------------+----------------+
| 9 | 102501350 | 1 | 6 | 349 | 2 | 1025 |
| 10 | 102501350 | 2 | 7 | 349 | 2 | 1025 |
| 11 | 102501350 | 1 | 9 | 349 | 2 | 1025 |
| 12 | 102501350 | 2 | 14 | 349 | 2 | 1025 |
+-----------------+------------+-------------------+-----------------+---------+-----------------+----------------+
4 rows in set (0.00 sec)

非常感谢任何帮助,非常感谢,Alan。

最佳答案

那是因为您每次都在创建新对象。使用 update_or_create 代替:https://docs.djangoproject.com/en/dev/ref/models/querysets/#update-or-create

关于mysql - Django:保存到数据库connundrun,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39425182/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com