Django CustomQuerySet仅适用于对象

2024-10-01 02:20:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用使用Custom QuerySet and Manager without breaking DRY?的CustomQuerySet。我只能使用objects访问自定义函数。这是我的密码:

class CustomQuerySetManager(models.Manager):
    """A re-usable Manager to access a custom QuerySet"""
    def __getattr__(self, attr, *args):
        print(attr)
        try:
            return getattr(self.__class__, attr, *args)
        except AttributeError:
            # don't delegate internal methods to the queryset
            if attr.startswith('__') and attr.endswith('__'):
                raise
            return getattr(self.get_query_set(), attr, *args)

    def get_query_set(self):
        return self.model.QuerySet(self.model, using=self._db)


class SampleModel(models.Model):
    objects = CustomQuerySetManager()

    class QuerySet(models.QuerySet):
        def test(self):
            print("test function was callsed")

在这种情况下:

SampleModel.objects.test() # This works
SampleModel.objects.all().test() # This doesnt works...

为什么会发生这种情况


Tags: andtestselfreturnobjectsmodelsdefmanager