给模型类动态添加方法

想要在每个类上加个方法或者property,一种可以每个类下加,另一种如下

def get_test(self):
    return 1

from django.contrib.contenttypes.models import ContentType
model_list = ['CommonSite']  # 或者也可以直接传类对象,下面就不用ContentType了
for obj in model_list:
    # ContentType.objects.get(model=obj).model_class().__dict__.update(get_test=get_test)  这句报错'dictproxy' object does not support item assignment
    # ContentType.objects.get(model=obj).model_class().get_test=get_test
    setattr(ContentType.objects.get(model=obj).model_class(), 'get_test', property(get_test))
    # setattr(CommonSite, 'get_test', property(get_test))
    print CommonSite.__dict__
    print CommonSite.get_test
    print CommonSite.objects.get(pk=1).get_test

 

posted on 2017-09-22 15:59  songbird  阅读(278)  评论(0编辑  收藏  举报