我有一个创建类的结构。
...Some code here...
def CreateClass(self, _context):
classname = _context.__name__ + "Test"
return type(classname, (viewsets.ModelViewSet,), {
'set_of_objects':_context.objects.all(),
'template_name': "base.html"
然后,当我调用这种结构时,我会上一些课:
bla-bla-bla
myClass = CreateClass(Foo)
我想自定义特定类的行为,所以我想手动创建它们。
例如,我可以创建一个类
class FooTest:
set_of_objects = FooSerializer(smth here)
template_name = "Foo.html"
问题是,当我调用此结构时,它会创建FooTest类,但该类已经存在于我的应用程序中。
我想写一个允许我的方法:
1. check if class with specific name already exist. (or is there some uniq class ID?)
2. If class already exist method should returns it
第一个问题,您能帮我吗?我查看了一些手册,但没有找到解决方案。
我已经尝试使用类似的东西
from django.apps import apps
cls = apps.get_model(app_label = 'base', model_name = 'FooTest')
问题是,当FooTest从models.Model(从django.db导入模型)继承时,此方法有效。
但是,如果根本不继承类,是否可以知道它是否存在? 对我来说,理想的解决方案-获得合格的班级名称。 例如,如果您打开外壳并像这样写smth
>>>from base.person.models.person import Person
>>>p = Person
>>>p
您可能会收到这样的东西
<class 'base.person.models.person.Person'>
如何获取此路径 base.person.models.person.Person ?
答案 0 :(得分:0)
对我来说,完全适合这样的解决方案
".".join([_context.__module__, _context.__name__])