0

I want to save my custom Model as Field in another Model as shown below. It's normal when I create and work with them during one session. But when I start a new session Django loads the Game model with player1 and player2 that have a null id.

Here example of my code

class Player(models.Model):

    name = models.CharField(max_length=40)

class Game(models.Model):
    player1 = Player()
    player2 = Player()

Sh. Andrey
  • 15
  • 5

3 Answers3

1

Seeing your comment. I think this is what you are going for.

class Player(models.Model):
    name = models.CharField(max_length=40)

class Game(models.Model):
    player1 = models.OneToOneField(Player, on_delete=models.CASCADE, related_name='p1_game')
    player2 = models.OneToOneField(Player, on_delete=models.CASCADE, related_name='p2_game')
Ayush Gupta
  • 1,166
  • 2
  • 9
  • 25
0

You need to create a foreign key, django's way of implementing a many-to-one relationship:

class Game(models.Model):
    player1 = models.ForeignKey(Player, on_delete=models.CASCADE, related_name="p1game")
    player2 = models.ForeignKey(Player, on_delete=models.CASCADE, related_name="p2game")

Don't forget to makemigrations and migrate!

user2390182
  • 72,016
  • 6
  • 67
  • 89
  • Thanks for the answer. But I don't want to have relationships many-to-one. Also, your variant wouldn't work, because player.game_set.create() - it becomes uncertain. – Sh. Andrey Oct 19 '21 at 15:20
0

You need to use a foreign key:

from django.contrib.gis.db import models

class Player(models.Model):
    name = models.CharField(max_length=40)

class Game(models.Model):
    player1 = models.ForeignKey(Player, on_delete=models.CASCADE)
    player2 = models.ForeignKey(Player, on_delete=models.CASCADE)

See What does on_delete do on Django models? for information about the on_delete argument.

  • Thanks for the answer. But here I would like to implement a one-to-one relationship. If it is possible. – Sh. Andrey Oct 19 '21 at 14:48
  • Also, this will result in clashes between player1 and player2. For example player = Player() player.game_set.create() - it become uncertain – Sh. Andrey Oct 19 '21 at 14:54
  • I added related names to disambiguate the reverse access. A one-to-one means that every player can be in at most two games. Once as player1 and once as player2. Is that what you are aiming for? – user2390182 Oct 19 '21 at 15:32