函数是否可以引用它所调用的类?

时间:2017-08-17 17:54:02

标签: python django model

我在Django中定义了一些模型,例如:

class Post(models.Model):
    text = models.CharField(max_length=50)

class Thread(models.Model):
    title = models.CharField(max_length=50)

我希望有一个外部函数,在这些类中调用,可以执行与调用它的类相关的函数。

例如,在ListAll()内部调用的Post()函数列出了所有Post个对象,但在Thread内调用,列出了所有Thread个对象。

我该怎么做?我已经看过使用__this__的回复,但显然引用了特定的类实例,这让我感到困惑。

谢谢。

2 个答案:

答案 0 :(得分:1)

您可以使用模型中的函数,可以使用类对象调用这些函数

class Thread(models.Model):
    title = models.CharField(max_length=50)

    def listAll(self):
        return self.objects.all() # a function that would return all objects

根据注释如果您需要为许多模型使用单个函数,则可以通过其名称动态加载模型。我不会说它推荐或其他任何东西,但它完美无缺。

import importlib
model_module = importlib.import_module('app_name.models.models') 
# remember this example refers to loading a module not its class so if you 
# have a file models.py containing all the models then this should be perfect
model_object = model_module.model_name # now you have loaded the model
data = model_object.objects.all() # apply whatever you want now

答案 1 :(得分:1)

这是mixin的工作,可以添加到任何类中。

class ListAll:
    def list_all(self):
        return self.__class__.objects.all()

将其添加到课程中:

class Post(ListAll, models.Model):
     ...

并使用它:

my_post_obj.list_all()

我希望这是一个例子,因为将模型类本身传递到你想要列出对象的任何地方会好得多。

相关问题