如何管理包含大量成员函数的Django模型?
我有一个很大的模型,因为它有很多成员函数。我想把这些函数按照它们的用途分成不同的类,这样一切会更有条理。
使用 OneToOneField
对我来说不是个好选择,因为我的应用程序非常依赖查询缓存(使用 cacheops)。我发现从数据库获取最新版本的数据对象时,可能会附带一个过时的 OneToOneField(来自缓存)。而且,数据成员的数量不是问题,主要是成员函数的数量。所以我更倾向于只使用一个数据模型。
比如,我可以这样做:
# models.py
class MyModel(models.Model):
# members
# separate member functions
class CustomModelFunctions:
@staticmethod
def some_function(my_model_instance):
# logic
# call the function on the my_model obj
# instead of calling my_model.some_function()
CustomModelFunctions.some_function(my_model)
这样是可行的,但问题是这些函数不能在 Django 模板中使用,因为 my_model 参数无法传递。例如,我不知道如何替换以下模板代码:
{% if my_model.some_function %}
有没有人知道解决这个问题的方法?或者有什么其他的方式来组织有很多成员函数的模型?
1 个回答
1
我有一个很大的模型,因为里面有很多成员函数。我想把这些函数按照它们的用途分成不同的类,这样一切会更有条理。
可能最好的办法是使用一个代理,比如:
class FunctionCategory(type):
def __get__(self, obj, objtype=None):
return self(obj)
class FunctionCategoryBase(metaclass=FunctionCategory):
def __init__(self, obj):
self.obj = obj
# separate member functions
class FunctionCategory1(FunctionCategoryBase):
def some_function11(self):
# use self.obj
return None
def some_function12(self):
# use self.obj
return None
# separate member functions
class FunctionCategory2(FunctionCategoryBase):
def some_function21(self):
# use self.obj
return None
def some_function22(self):
# use self.obj
return None
def some_function23(self):
# use self.obj
return None
class MyModel(models.Model):
# members
functions1 = FunctionCategory1
functions2 = FunctionCategory2
然后你可以使用:
my_model_object.functions1.some_function12()
这样,对于 my_model_object.functions1
,就会创建一个 FunctionCategory1
,并把模型对象注入进去。