views:

34

answers:

1

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

+1  A: 

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.

Chris Lawlor
Thanks. Is there a way to make it unidirectional?I worked with Hibernate for several years and really like their approach for bi/uni-directional relations. i couldn't find a similar approach in django.
Liz
I don't think the concept really applies in Django. This looks like a pretty standard M2M relationship no matter what framework you are using. What is it that you are concerned about?
Chris Lawlor
My concern is that in my application logic the file is not supposed to be aware of the existence of a file group - so I wanted to avoid bidirectional relation. It's not a technical issue, but rather a concept.
Liz
No matter which model the FK is on, you can still 'find' the other in SQL using a simple JOIN... This is totally independent of any ORM framework. I've not used Hibernate, but it seems that the uni/bi directional concept is something unique to that framework. If you are referring to the File being 'aware' of the FileGroup from a normalization perspective, the lookup table created by Django's ManyToManyField is totally appropriate.
Chris Lawlor
Thanks for the help!
Liz