如何为相关对象创建自定义管理器?

我有这些相关的模型,并且有一个自定义管理器

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用于设备设置?


不要介意在管理器上调用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名称。

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

上一篇: How to create a custom manager for related objects?

下一篇: How to implement EAV in Django