作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我认为以下内容非常有效:
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)。我可以在我的表单中选择它们并更新但是当代码运行时它只是向表中添加另外两行而不是更新当前行。检查是否需要更新的一组新团队选择很简单:
如上所述,它目前只添加了两个新行,如下所示:
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/
我是一名优秀的程序员,十分优秀!