[Django]-Make a One to Many Relation in django

17๐Ÿ‘

โœ…

As Arthur states, this is documented quite well in the Django documentation.

It is in fact quite easy:

from django.db import models

class Person(models.Model):
    # Some other fields
    group = models.ForeignKey(Group, related_name='people')

class Group(models.Model):
    # Some fields

As you can see, you simply create a foreign key in the person class -> this is quite equivalent to how you would set it up manually in the database, if you should do so.

Django will automatically add the reverse relation, such that you can find people from a group:

some_group.people

Note that the related_name specifies the name of the reverse relation. This is optional, but I guess you want to use people instead of persons.

๐Ÿ‘คnilu

Leave a comment