Home > Blockchain >  Django set relation between two models
Django set relation between two models

Time:10-20

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

CodePudding user response:

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.

CodePudding user response:

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!

CodePudding user response:

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')
  • Related