[Django]-Django direction of Many-to-Many relationship

4👍

“Generally, ManyToManyField instances should go in the object that’s going to be edited on a form. In the above example, toppings is in Pizza (Article) (rather than Topping (Topics) having a pizzas (article) ManyToManyField ) because it’s more natural to think about a pizza (article) having toppings (topics) than a topping (topic) being on multiple pizzas (articles). The way it’s set up above, the Pizza (Article) form would let users select the toppings (topics).” –docs

Just quoting because it’s interesting the doc’s emphasis is more on the UI than the ORM.

Also you’re probably already doing this by just in case, I like to interact with my app via the shell to try out different queries in situations like this.

0👍

I would say you work things top -> down. Which is the top level object should have the relation description (ManyToManyField).

Why? Look at things from user interface point of view. You present the list of TOPICS or FORUMS before you go into articles and threads. RESTful urls also follow this logic as urls usually have TOPIC/topic_id/post/post_id/ not the other way around. For this reason I think it makes sense to add ManyToManyField to Topic not post, to Forum not article/thread.

You also get to use cool django stuff like

Topic.objects.get(id = topic_id).select_related()

My 2 cents anyway.

Edit1

I do not follow this advice all the time. For example:

There is Person and there is Group, which is meant to identify bunch of Persons. Where to put manytomanyfield there? Django, has put the manytomany connection to its Person (django.contrib.auth.models class User via mixin) not Group. I have done it the other way around in one case. Why? Because i wanted users to be able to add Person’s to Group in Group’s view not Person’s view. And i did not want to do something like looping through bunch of persons to add single group to each of them. Looking back at this i still do not know if it was bad or good decision because it would have brought me problems either way 😛

So i guess i want to say that you should evaluate each case separately and always think ahead about what you want to do with each class and object in the future.

/Edit1

Leave a comment