Search code examples
djangodjango-modelsentity-relationship

unidirectional one-to-many and many-to-may in django


I'm new to django. I have 2 simple objects, lets call them - File and FileGroup: - A FileGroup can hold a list of files, sorted according to an 'order' field. - Each file can be associated with multiple groups.

so basically, the db tables would be: 1) File 2) File_Group 3) File_Group_Mapping table that has a column named "order" in addition to the fk to the file and file group.

There is a many-to-many relationship here, but the File object is not supposed to be aware of the existence of the FileGroup (doesn't make sense in my case)

My questions - Is there a way to create a unidirectional many-to-many/one-to-many relationship here? How can I model it with django?

I couldn't find a way to make it unidirectional via django. I saw a solution that uses something like -

class FileGroup(...):
    files = models.ManyToManyField(File, through='FileGroupMapping')

but this will make the File object aware of the FileGroup.

I can also do this via mapping the File_Group_Mapping table in the models file like this -

class FileGroupMapping(...):
     files = models.ForeignKey(File)
     groups = models.ForeignKey(FileGroup)
     order = models...

What is the best way to do this via django?

Thanks


Solution

  • Your two approaches are identical. Behind the scenes, Django creates a lookup table for a ManyToManyField. From the ORM perspective, you can put the ManyToManyField on either model, although it makes a difference in the admin, and if you wish to use the 'limit_choices_to' option. Using 'through' lets you add columns to the lookup table to further define the relationship between the two models, which is exactly what you've done by manually creating the lookup table.

    Either way, you can still 'get' the FileGroup that a particular File belongs to, as Django querysets will follow a FK relationship bidirectionally.