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

0

Issue

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)

Solution

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

Answered By - arjun

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More