为什么我不能将列表理解传递给 Django RelatedManager add()?
Why can't I pass a list comprehension to Django RelatedManager add()?
鉴于:
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)
此 OpenChallenge
方法代码有效:
for p in self.rengo_black_team.all():
self.game.rengo_black_team.add(p)
但是这段代码没有:
self.game.rengo_black_team.add([x for x in self.rengo_black_team.all()])
基于最后一个例子 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)
看来我的示例应该有效,但我得到
“字段 'id' 需要一个数字但得到了 []”
您必须解压缩列表,因为 add
期望对象作为位置参数而不是列表传递,所以:
self.game.rengo_black_team.add(*[x for x in self.rengo_black_team.all()])
或者只是:
self.game.rengo_black_team.add(*self.rengo_black_team.all())
鉴于:
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)
此 OpenChallenge
方法代码有效:
for p in self.rengo_black_team.all():
self.game.rengo_black_team.add(p)
但是这段代码没有:
self.game.rengo_black_team.add([x for x in self.rengo_black_team.all()])
基于最后一个例子 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)
看来我的示例应该有效,但我得到
“字段 'id' 需要一个数字但得到了 [
您必须解压缩列表,因为 add
期望对象作为位置参数而不是列表传递,所以:
self.game.rengo_black_team.add(*[x for x in self.rengo_black_team.all()])
或者只是:
self.game.rengo_black_team.add(*self.rengo_black_team.all())