Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django calling save on a QuerySet object - 'QuerySet' object has no attribute 'save'

Tags:

python

django

How would I get the below to work?

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 when the object already exists in the datbase then I get:

'QuerySet' object has no attribute 'save'.

In terms of my Models, GameParticipant has ForeignKey to both Game and Player. I understand that filter returns a QuerySet but I'm not sure how to cast that to a GameParticipant or is that not the right thinking?

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)

OR IS THERE A BETTER WAY TO DO WHAT IM TRYING TO DO? ie. with a .get() instead of a .filter() but then i run into other issues???

like image 988
Kamilski81 Avatar asked Jun 02 '11 23:06

Kamilski81


4 Answers

You'll want to use the update method since you're dealing with multiple objects:

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

like image 117
brianz Avatar answered Nov 03 '22 07:11

brianz


filter returns a queryset. A queryset isn't a single object, it's a group of objects so it doesn't make sense to call save() on a queryset. Instead you save each individual object IN the queryset:

game_participants = GameParticipant.objects.filter(player=player, game=game)
for object in game_participants:
    object.save()
like image 34
Timmy O'Mahony Avatar answered Nov 03 '22 07:11

Timmy O'Mahony


It is possible to get this error by assigning not saved object to another object foreign field.

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

and the right way of this is:

    day.save()
    for project in projects:
        project.day = day
like image 2
MightyPixel Avatar answered Nov 03 '22 07:11

MightyPixel


filter return a list and if your want a specific single object from it you need give the index of that object

game_participant = GameParticipant.objects.filter(player=player, game=game)[0]
like image 2
MD SHAYON Avatar answered Nov 03 '22 07:11

MD SHAYON