0
我有一个django模型需要做一些处理引用自定义用户模型。懒惰类属性修饰器
我无法在类加载时使用此模型的类,因为类的加载顺序未知。
所以我需要添加一些类属性在运行时,在我加入他们在__init__
或__new__
喜欢的时刻:
def __new__(cls, *args, **kwargs):
# hack to avoid INSTALLED_APPS initialization conflicts.
# get_user_model() can't be called from this module at class loading time,
# so some class attributes must be added later.
# Metaclasses could me more appropiate but I don't want to override
# dango's metaclasses.
if not hasattr(cls, '_reverse_field_name_to_user'):
cls._find_reverse_field_name_to_user()
return Group.__new__(cls, *args, **kwargs)
它的工作原理,但看起来可怕,所以我想过使用的东西像@lazyclassproperty
这些属性。
我发现了几个@classproperty
和@lazyproperty
装饰器,但两个都没有,我也不知道如何自己写一个装饰器。
问题:我怎么能编码这样的装饰?或者建议另一种更清洁的替代方案来实现我目前愚蠢的实施。
工程就像一个魅力。非常感谢,我希望我能不止一次地开心! –