Python Django在QuerySet对象上调用save-';QuerySet';对象没有属性';保存';

Python Django在QuerySet对象上调用save-';QuerySet';对象没有属性';保存';,python,django,Python,Django,我如何让下面的工作 player = Player.objects.get(pk=player_id) game = Game.objects.get(pk=game_id) game_participant = GameParticipant.objects.filter(player=player, game=game) game_participant.save() I当对象已存在于数据库中时,我得到: “QuerySet”对象没有属性“save” 就我的机型而言,GamePartici

我如何让下面的工作

player = Player.objects.get(pk=player_id)
game = Game.objects.get(pk=game_id)
game_participant = GameParticipant.objects.filter(player=player, game=game)
game_participant.save()
I当对象已存在于数据库中时,我得到:

“QuerySet”对象没有属性“save”

就我的机型而言,
GameParticipant
Game
Player
都有
ForeignKey
。我知道filter会返回一个QuerySet,但我不确定如何将其转换为
游戏参与者
,或者这不是正确的想法

class Player(models.Model):
    name = models.CharField(max_length=30)
    email = models.EmailField()

class Game(models.Model):
    game_date = models.DateTimeField()
    team = models.ForeignKey(Team)
    description = models.CharField(max_length=100, null=True, blank=True)
    score = models.CharField(max_length=10, null=True, blank=True)

class GameParticipant(models.Model):
    STATUS_CHOICES = (('Y','Yes'),('N','No'),('M','Maybe'))
    status = models.CharField(max_length=10, choices=STATUS_CHOICES)
    game = models.ForeignKey(Game)
    player = models.ForeignKey(Player)

还是有更好的方法来做我想做的事情?例如,使用.get()而不是.filter(),但我遇到了其他问题???

filter返回查询集。queryset不是单个对象,而是一组对象,因此对queryset调用save()没有意义。而是将每个对象保存在查询集中:

game_participants = GameParticipant.objects.filter(player=player, game=game)
for object in game_participants:
    object.save()

您需要使用
update
方法,因为您正在处理多个对象:


将未保存的对象指定给另一个对象外部字段可能会出现此错误

    for project in projects:
        project.day = day
    day.save()
正确的方法是:

    day.save()
    for project in projects:
        project.day = day
这是将数据保存到Django 2.2中新增的queryset中的一种好方法:


当你使用queryset时,它可能会返回一个列表,说明你为什么要使用它

game_participant = GameParticipant.objects.filter(player=player, game=game)[0]
而不是

game_participant = GameParticipant.objects.filter(player=player, game=game)

试试这个对我有用的过滤器

返回一个列表,如果你想从中得到一个特定的对象,你需要给出该对象的索引

game_participant = GameParticipant.objects.filter(player=player, game=game)[0]

你能为游戏参与者发布你的模型代码吗?检查并确保您正在扩展模型。模型也是预期的。您的模型应该有类似于
类GameParticipant(models.model)
的内容。为什么要保存刚刚从数据库加载的内容而不进行修改?
game_participant = GameParticipant.objects.filter(player=player, game=game)
game_participant = GameParticipant.objects.filter(player=player, game=game)[0]