gpt4 book ai didi

Django RelatedManager 的.create() 用法?

转载 作者:行者123 更新时间:2023-12-04 03:20:02 27 4
gpt4 key购买 nike

我有两个模型:PlayPlayParticipant,(部分)定义为:

class PlayParticipant(models.Model):
player = models.ForeignKey('Player')
play = models.ForeignKey('Play')
note = models.CharField(max_length=100, blank=True)

我的一段代码有一个播放 p,它的 ID 为 8581,我想向其中添加参与者。我正在尝试使用 RelatedManager 的 .create() 来做到这一点,例如:

p.playparticipant_set.create(player_id=2383)

Django 从中构建:

INSERT INTO `api_playparticipant` (`player_id`, `play_id`, `note`) VALUES (2383, 2383, '')

这是 Django 中的错误,还是我误用了 .create()

复制粘贴 shell 以进行完整性检查:

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`))')

来自查询日志:

5572 Query       INSERT INTO `api_playparticipant` (`player_id`, `play_id`, `note`) VALUES (2383, 2383, '')

最佳答案

我不明白你的第一个例子怎么会是一个错误?这种行为是完全直观的。您的 p 是一个 ID 为 2383 的 play,并且您在其相关集上调用 create 方法。您还指定了一个名为 player_id 的额外字段,并将其值设为 2383。两个游戏 ID 均为 2383 是合乎逻辑的(因为这是包含此相关集的游戏的 ID)并且该玩家 ID 也将是 2383(因为您明确传递了该值)。

您的第二个示例似乎表明存在错误,但我无法重现它。这是我的模型:

class Player(models.Model):
name = models.CharField(max_length=100)

class Play(models.Model):
title = models.CharField(max_length=100)

class PlayParticipant(models.Model):
player = models.ForeignKey('Player')
play = models.ForeignKey('Play')
note = models.CharField(max_length=100, blank=True)

这是 shell 输出:

>>> player1 = Player.objects.create()
>>> player2 = Player.objects.create()
>>> player1.id
2
>>> player2.id
3
>>> play1 = Play.objects.create()
>>> play2 = Play.objects.create()
>>> play1.id
3
>>> play2.id
4
>>> pp1 = play1.playparticipant_set.create(player_id=2)
>>> pp1.play.id
3
>>> pp1.player.id
2

无论如何,您为什么要将此发布到 SO? Django 有一个错误追踪器、几个活跃的官方邮件列表和几个 IRC channel 。

关于Django RelatedManager 的.create() 用法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1101613/

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