我有这些相关模型,其中一个有自定义管理器
class Device(Model): name = CharField() class DeviceSettingManager(Manager): use_for_related_fields = True class Setting(Model): name = CharField() value = CharField() device = ForeignKey(Device, related_name='settings') objects = DeviceSettingManager
但是当我运行Django shell时,我看到正在使用的“RelatedManager”管理器
>>> d = Device.objects.all()[0] >>> type(d.settings) django.db.models.fields.related.create_foreign_related_manager..RelatedManager
如何让DeviceSettingManager用于设备的设置?
答案 0 :(得分:1)
不要介意在管理员上调用type()
的结果,DeviceSettingManager
实际上正在使用中。您可以通过执行以下操作来检查:
class DeviceSettingManager(models.Manager):
use_for_related_fields = True
def manager_status(self):
print("Device Setting Manager is Active")
并致电:
>>> d = Device.objects.all()[0]
>>> d.settings.manager_status()
Device Setting Manager is Active
即使您明确地将经理传递给相关对象,例如:
>> d.settings(manager="settings_objects")
当然:
class Setting(Model):
name = CharField()
value = CharField()
device = ForeignKey(Device, related_name='settings')
settings_objects = DeviceSettingManager() # Notice the parenthesis
经理的class
仍会显示为:django.db.models.fields.related_descriptors.create_reverse_many_to_one_manager.<locals>.RelatedManager
别介意class
名称。