Home > database >  How to create model with relationship one-to-many in Django?
How to create model with relationship one-to-many in Django?

Time:12-16

I need create relationship one-to-many. One Group can have many members.

Did I do it right?

Model:

class Group(models.Model):
    id = models.BigAutoField(primary_key=True)
    groupName: models.CharField(max_length=100)
    description: models.CharField(max_length=255)
    createdAt = models.DateTimeField(auto_now_add=True)
    updatedAt = models.DateTimeField(auto_now=True)
    members: models.ForeignKey(User, n_delete=models.CASCADE)

CodePudding user response:

ForeignKey represents ManyToOne relationship so here according to your model One member will have many groups.

If you want one group will have many members then the models should be like this.


class Group(models.Model):
    id = models.BigAutoField(primary_key=True)
    groupName: models.CharField(max_length=100)
    description: models.CharField(max_length=255)
    createdAt = models.DateTimeField(auto_now_add=True)
    updatedAt = models.DateTimeField(auto_now=True)

class Member(models.Model):
   group = models.ForeignKey(Group)
   ......
    
  • Related