Django对QuerySet对象调用save-“QuerySet”对象没有属性“save”

2024-05-11 18:22:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我怎样才能让下面的工作?

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()

当对象已经存在于数据库中时,我得到:

'QuerySet' object has no attribute 'save'.

就我的模型而言,GameParticipantGamePlayer都有ForeignKey。我知道过滤器返回一个QuerySet,但我不确定如何将其转换为一个GameParticipant,或者这不是正确的想法?

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(),但我遇到了其他问题???


Tags: gametruegetmodelobjectsmodelslengthmax
3条回答

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

https://docs.djangoproject.com/en/2.0/topics/db/queries/#updating-multiple-objects-at-once

通过将未保存的对象分配给另一个对象外部字段,可能会出现此错误。

    for project in projects:
        project.day = day
    day.save()

正确的方法是:

    day.save()
    for project in projects:
        project.day = day

过滤器返回一个queryset。queryset不是单个对象,而是一组对象,因此对queryset调用save()是没有意义的。相反,您可以在queryset中保存每个单独的对象:

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

相关问题 更多 >