【问题标题】:Custom many to one manager on self自定义多对一经理
【发布时间】:2017-01-09 21:00:06
【问题描述】:

我正在尝试在我的模型上使用自定义管理器,但希望它也用于自我关系中,因此我可以向 add 方法添加一些代码。代码如下:

from django.db import models

class TestModelManager(models.Manager):

    use_for_related_fields = True

    def __init__(self):
        models.Manager.__init__(self)

    def add(self, *args, **kwargs):
        print('My custom code.')
        super().add(*args, **kwargs)

class TestModel(models.Model):

    objects = TestModelManager()

    name = models.CharField(max_length=50)
    parent = models.ForeignKey(
        'self',
        related_name='children',
        null=True,
        blank=True,
    )

Python shell 输出

>>> from testmods.models import TestModel
>>> TestModel.objects
<testmods.models.TestModelManager object at 0x10bc96e80>
>>> TestModel.objects.bulk_create([TestModel(name="foo"), TestModel(name="bar")])
[<TestModel: TestModel object>, <TestModel: TestModel object>]
>>> t1, t2 = TestModel.objects.all()
>>> t1.children.add(t2)
>>> t1.children.all()
<QuerySet [<TestModel: TestModel object>]>
>>> 

t1.children.add(t2) 行中为什么不打印“我的自定义代码。”?

【问题讨论】:

    标签: django python-3.x model


    【解决方案1】:

    我发现我的答案是仔细阅读源代码。看来add方法是添加到自定义管理器中的,不能在上述方法中修改。

    def create_reverse_many_to_one_manager(superclass, rel):
        """
        Create a manager for the reverse side of a many-to-one relation.
        This manager subclasses another manager, generally the default manager of
        the related model, and adds behaviors specific to many-to-one relations.
        """
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-01-09
      • 1970-01-01
      • 1970-01-01
      • 2019-02-07
      • 1970-01-01
      • 2021-07-19
      • 1970-01-01
      • 2010-12-04
      相关资源
      最近更新 更多