想要在每个类上加个方法或者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
时间: 2024-10-03 15:48:48