I have two models: Play and PlayParticipant, defined (in part) as:
class PlayParticipant(models.Model):
player = models.ForeignKey('Player')
play = models.ForeignKey('Play')
note = models.CharField(max_length=100, blank=True)
A piece of my code has a play p which has id 8581, and I’d like to add participants to it. I’m trying to use RelatedManager’s .create() to do that, like:
p.playparticipant_set.create(player_id=2383)
From which, Django constructs:
INSERT INTO `api_playparticipant` (`player_id`, `play_id`, `note`) VALUES (2383, 2383, '')
Is this a bug in Django, or am I misusing .create()?
Copy-pasting shell for sanity check:
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`))')
From query.log:
5572 Query INSERT INTO `api_playparticipant` (`player_id`, `play_id`, `note`) VALUES (2383, 2383, '')
I don’t see how is your first example supposed to be a bug? This behavior is completely intuitive. Your p is a play with an id of 2383, and you’re calling the create method on its related set. You’re also specifying an extra field, called player_id, and giving it a value of 2383. It’s only logical that both play id will be 2383 (because that’s the id of the play containing this related set) and that player id will also be 2383 (because you explicitly passed that value in).
Your second example would seem to indicate a bug, but I cannot reproduce it. Here are my models:
Here’s the shell output:
In any case, why are you posting this to SO? Django has a bugtracker, a couple of active official mailing lists and a couple of IRC channels.