[英]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. Django 的ForeignRelatedObjectsDescriptor.create_manager(...)
函数动态创建了RelatedManager
类,然后初始化动态创建的类的实例。
If I wanted to override the RelatedManager.add(...)
method, how would I do it?如果我想覆盖RelatedManager.add(...)
方法,我该怎么做?
The RelatedManager
classes are created in file: django/db/models/fields/related.py
. RelatedManager
类在文件中创建: django/db/models/fields/related.py
。
An example of how I'd like to use a custom RelatedManager
is...我想如何使用自定义相关RelatedManager
器的一个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.任何建议将不胜感激。
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.但是要回答这个问题,您可以在模型上定义一个自定义管理器并设置use_for_related_fields=True
以确保它被用作自动管理器。 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.我有一个自定义管理器,它覆盖self._db
和get_query_set()
以将其路由到不同的数据库。
I dynamically created a model class, and has its _default_manager
set with my custom manager.我动态创建了一个模型类,并使用我的自定义管理器设置了它的_default_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
.这适用于类本身,但不适用于相关字段(foreign 或 many2many),即使我确实设置了 set set 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.对于相关字段,附加db_manager(dbname)
(例如, record.managed_set.db_manager(dbname)
)可以修复all()方法,但不能修复add()方法。
To understand what I mean, see this django ticket: http://code.djangoproject.com/ticket/13358要理解我的意思,请参阅此 django 票证: http : //code.djangoproject.com/ticket/13358
I think it works for all()
, but not add()
.我认为它适用于all()
,但不适用于add()
。
RelatedManager.add()
calls RelatedManager._add_items()
which calls Manager.bulk_create()
. RelatedManager.add()
调用RelatedManager._add_items()
调用Manager.bulk_create()
。
So if you extend Manager.bulk_create()
, you might be able to achieve what you are after.因此,如果您扩展Manager.bulk_create()
,您可能能够实现您所追求的目标。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.