我有两个模型:Play
和PlayParticipant
,(部分)定义为:
class PlayParticipant(models.Model):
player = models.ForeignKey('Player')
play = models.ForeignKey('Play')
note = models.CharField(max_length=100, blank=True)
我的一段代码有一个p
id 为 8581 的 play,我想向其中添加参与者。我正在尝试使用 RelatedManager.create()
来做到这一点,例如:
p.playparticipant_set.create(player_id=2383)
Django从中构造:
INSERT INTO `api_playparticipant` (`player_id`, `play_id`, `note`) VALUES (2383, 2383, '')
这是 Django 中的错误,还是我在滥用.create()
?
复制粘贴外壳以进行完整性检查:
In [17]: p = Play.objects.get(id=8581)
In [18]: p.id
Out[18]: 8581L
In [19]: p.playparticipant_set.create(player_id=2383)
...
IntegrityError: (1452, 'Cannot add or update a child row: a foreign key constraint fails (`gc/api_playparticipant`, CONSTRAINT `play_id_refs_id_60804ffd462e0029` FOREIGN KEY (`play_id`) REFERENCES `api_play` (`id`))')
从查询.log:
5572 Query INSERT INTO `api_playparticipant` (`player_id`, `play_id`, `note`) VALUES (2383, 2383, '')