开发者

Overriding Django's RelatedManager methods

Django's Forei开发者_如何学CgnRelatedObjectsDescriptor.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().


RelatedManager.add() calls RelatedManager._add_items() which calls Manager.bulk_create().

So if you extend Manager.bulk_create(), you might be able to achieve what you are after.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜