Saving data to Django database with Views

Viewed 280

I need help with one thing in my django project.

I have class games_renderer in my views.py which is connected to the path in URLs. I need this class to take three values and then store them in the SQL database in Django in the created UserGameScore model. I tried to do this using model.object.score but the application reports an error. I think the problem is that the application does not know which line to assign the value to, but I do not know where I can determine this value, using the value player_id. The Game_id value is used to specify in which column the value is to be written.

views.py

def games_renderer(request, game_id, player_id, score):

if game_id == 1:
    
        UserGameScore.objects.create(game1_score = score)
elif game_id ==2:
    UserGameScore.objects.create(game2_score = score)
elif game_id ==3:
    UserGameScore.objects.create(game3_score = score)
else:
    return render(request, 'result.html',{'game_id' : game_id, 'player_id' : player_id, "score" : score}   )

models.py

class UserGameScore(models.Model):
    user_rec = models.ForeignKey(User, on_delete=models.CASCADE)
    game1_score = models.IntegerField(null=True, blank=True)
    game2_score = models.IntegerField(null=True, blank=True)
    game3_score = models.IntegerField(null=True, blank=True)
1 Answers

You can try this.

def games_renderer(request, game_id, player_id, score): 
    game_score = UserGameScore() 
    if game_id === 1: 
         game_score.game1_score = score 
    if game_id === 2: 
        game_score.game2_score = score 
    if game_id === 3: 
        game_score.game3_score = score 
    game_score.save()

You can also change your model to simplify your view. Here is a small suggestion.

class UserGameScore(models.Model):
    GAME_CHOICES = [
    (ONE, '1'),
    (TWO, '2'),
    (THREE, '3'),
    ]
    user_rec = models.ForeignKey(User, on_delete=models.CASCADE)
    score = models.IntegerField(null=True, blank=True)
    game_type = models.CharField(
        max_length=2,
        choices=GAME_CHOICES,
        default=ONE,
    )

Your view should look similar to this:

def games_renderer(request, game_id, player_id, score): 
    game_score = UserGameScore(user_rec=player_id, score=score, game_type=game_id ) 
Related