Search code examples
pythondjangodjango-modelsmany-to-many

Custom Managers and "through"


I have a many-to-many relationship in my django application where I use the "add" method of the manager pretty heavily (ie album.photos.add() ).

I find myself needing to store some data about the many-to-many relationship now, but I don't want to lose the add method. Can I just set a default value for all the additional fields on the "through" model and somehow re-implement the add method?

I don't really know much about custom managers but I suspect that might be the right place to look.

Update:

Been reading up on custom managers. Maybe I can just keep the add/remove/etc from being disabled when I add the "through" argument to my Many-to-many field?

Does anyone know how to do that?


Solution

  • Simplest way is to just add a method to Album (i.e. album.add_photo()) which handles the metadata and manually creates a properly-linked Photo instance.

    If you want to get all funky, you can write a custom manager for Photos, make it the default (i.e. first assigned manager), set use_for_related_fields = True on it, and give it an add() method that is able to properly set the default metadata for the relationship.

    Aside: seems like it wouldn't be too hard for Django to make this generic; instead of removing the add() method when there's a through table, just make add() accept arbitrary kwargs and treat them as data for the through table.