In Django's models.Manager create method, how do I store a random object in a foreignkey field?

Viewed 16

I am able to create Game objects that have the product_selection field being populated correctly, but for some reason, the correct_product field is not getting populated. Why is that?

Here is my code from models.py:

import random

class GameManager(models.Manager):
    def create_game(self, player):
        game = self.create(player = player)
        product_selection = random.sample(list(Product.objects.exclude(users_who_viewed=player)),3)
        game.product_selection.set(product_selection)
        game.correct_product = random.choice(product_selection)
        return game

class Game(models.Model):
    player = models.ForeignKey(User, on_delete= models.CASCADE,related_name='costcorrect_player')
    score = models.IntegerField(default=0)
    product_selection = models.ManyToManyField(Product, blank=True, null=True)
    correct_product = models.ForeignKey(Product, on_delete= models.CASCADE, related_name='costcorrect_correct_product', null=True)

    objects = GameManager()
1 Answers

You just need to call .save() at the end of the method instead of just return.

If you take your create_game code out of the GameManager class as it's own independent function then you can pass it to the field default and it will call the function:

def create_game():
   ...
   return game_objects

class Game(models.Model):
   ...

   product_selection = models.ManyToManyField(..., default=create_game)
Related