Why can't I pass a list comprehension to Django RelatedManager add()?
Given:
class Game(models.Model):
rengo_black_team = models.ManyToManyField(Player)
class OpenChallenge(CommonChallenge):
rengo_black_team = models.ManyToManyField(Player)
game = models.ForeignKey(Game, on_delete=models.CASCADE)
This OpenChallenge
method code works:
for p in self.rengo_black_team.all():
self.game.rengo_black_team.add(p)
But this code does not:
self.game.rengo_black_team.add([x for x in self.rengo_black_team.all()])
Based on the last example in the docs ,
>>> john = Author.objects.create(name="John")
>>> paul = Author.objects.create(name="Paul")
>>> george = Author.objects.create(name="George")
>>> ringo = Author.objects.create(name="Ringo")
>>> entry.authors.add(john, paul, george, ringo)
it seems like my example should work, but I get
"Field 'id' expected a number but got [<Player: anoek>]"
You will have to unpack the list, since add
expects the objects to be passed as positional arguments and not as a list, so:
self.game.rengo_black_team.add(*[x for x in self.rengo_black_team.all()])
or just:
self.game.rengo_black_team.add(*self.rengo_black_team.all())