简体   繁体   中英

Can you create instances of two foreign keys referencing the same model in one model?

I'm trying to create two instances of a model class called Team. I want to create two fields stored in my GameId Model called home and visitor. These two foreign keys are referenced from the same model called Team. Should I use a foreign key or many to many field relationship?

Background of models:

  • One team can have many gameids
  • One gameid should have 2 teams

     class GameId(models.Model): week = models.CharField(max_length = 100) day = models.CharField(max_length = 100) home = models.ForeignKey(Team, on_delete=models.SET_NULL, null = True, related_name='home') visitor = models.ForeignKey(Team, on_delete=models.SET_NULL, null = True, related_name='visitor') gameid = models.CharField(max_length = 100, blank=True) slug = models.SlugField(max_length=100, unique=True, blank=True) 

If a gameID can hold more than 1 team then it is needed to be set to ManyToMany .

class GameId(models.Model):

    week = models.CharField(max_length = 100)
    day = models.CharField(max_length = 100)
    home = models.ManyToMany(Team, related_name='home')
    visitor = models.ForeignKey(Team, on_delete=models.SET_NULL, null = True, 
    related_name='visitor')

    gameid = models.CharField(max_length = 100, blank=True)
    slug = models.SlugField(max_length=100, unique=True, blank=True)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM