[Answered ]-Many to many vs new object with compound foreign keys in django

2👍

✅

Example number two is used when you have additional fields in your intermediary table (which the example does not have). Example number one will suffice when you don’t.

0👍

The advantage of the first case is that Pizza.toppings is a convenient way of accessing all the toppings for a pizza. In the second case, you’d have to say something like Topping.objects.filter(pizzatopping_set__pizza=pizza), which is awkward.

If you need extra data on the intermediary table (PizzaTopping) you will have to define the table explicitly. It’s still up to you, though, whether to add the ManyToMany field to Pizza (with a through keyword), and that again depends on whether you want convenient access to Pizza.toppings.

If you’re using the admin site there are advantages to the first case as well. For example, it can be nice to be able to say stuff like list_filter = ('toppings__price',).

In summary, I’d say it’s almost always a good idea to use the ManyToManyField, only making the intermediary table explicit when you need to add additional fields (or otherwise customize the table).

Leave a comment