Home > Software engineering >  Multiple many-to-many relations through the same model in Django problem
Multiple many-to-many relations through the same model in Django problem

Time:03-05

i have a problem i don't know how to make multiple many-to-many relations through the same model.

This is my DB relations :

Db architecture

and this is my code, i want to know if what I did is right or not ?

class Projects(models.Model):

  Project_name = models.CharField(max_length=50)
  Poject_key = models.CharField(max_length=50)
  CITools = models.ForeignKey(CITools,null=True,on_delete=models.CASCADE)

  UsersO = models.ManyToManyField(User,through='OwnerShips') # for user Ownerships
  UserF = models.ManyToManyField(User,through='Favorites') # for user Favorites

This is my OwnerSHips class :

class OwnerShips(models.Model):
  user = models.ForeignKey(User,on_delete=models.CASCADE)
  project = models.ForeignKey(Projects,on_delete=models.CASCADE)

And this is my Favorites Class:

class Favorites(models.Model):
  user = models.ForeignKey(User,on_delete=models.CASCADE)
  project = models.ForeignKey(Projects,on_delete=models.CASCADE)

CodePudding user response:

I don't think you can use foreign keys (ownerships and favorites) in Project before those classes are created.

CodePudding user response:

Actually i found the solution, i used the attribute related_name, so Django to create this two tables automatically

  • Related