Overriding Django's RelatedManager methods

Django's ForeignRelatedObjectsDescriptor.create_manager(...) function dynamically creates the RelatedManager classes and subsequently initializes an instance of the dynamically created class.

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

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

An example of how I'd like to use a custom RelatedManager is...

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.


I'm not sure what you need the override for - the default queryset already does what you want.

But to answer the question, you can define a custom Manager on the model and set use_for_related_fields=True to ensure it gets used as the automatic manager. See the documentation on controlling automatic Manager types.


I think I am having the same problem.

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

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

This works for the class itself, but not for related field (foreign or many2many), even though I did set sets use_for_related_fields = True .

For related field, appending db_manager(dbname) (for example, record.managed_set.db_manager(dbname) ) can fix all() method, but not for 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() .

链接地址: http://www.djcxy.com/p/4326.html

上一篇: GPU是否适合大小写

下一篇: 重写Django的RelatedManager方法