Overriding Django RelatedManager Methods

Function

Django ForeignRelatedObjectsDescriptor.create_manager(...) dynamically creates RelatedManager classes and then initializes an instance of the dynamically created class.

If I wanted to override the RelatedManager.add(...) method, how would I do it?

RelatedManager classes are created in the file: django/db/models/fields/related.py .

An example of how I would like to use a custom RelatedManager , ...

 class Record(Model): string = CharField() class Managed(Model): record = ForeignKey('Record') boolean = BooleanField() def view_function(...): record = Record(string='Example') record.save() record.managed_set.add(Managed(boolean=True)) # How to override add()? 

Any suggestions would be appreciated.

+7
source share
2 answers

I'm not sure what you need to override - the default set of queries already does what you want.

But to answer the question, you can define a user manager on the model and set use_for_related_fields=True to make sure that it is used as an automatic manager. See the documentation Managing Automated Manager Types .

+3
source

I think I have the same problem.

I have a custom manager that overrides self._db and get_query_set() to redirect it to different databases.

I dynamically created a model class and has my _default_manager set with my custom manager.

This works for the class itself, but not for a sibling field (foreign or many2many), although I set the set use_for_related_fields = True .

In the corresponding field, adding db_manager(dbname) (for example, record.managed_set.db_manager(dbname) ) can fix the all () method, but not for the add () method.

To understand what I mean, see this django ticket: http://code.djangoproject.com/ticket/13358

I think it works for all() , but not add() .

0
source

All Articles