在不访问数据库的情况下从模型类切换到代理类:
class EntryProxy(Entry): @property def category(self): new_inst = EntryProxy() new_inst.__dict__ = super(EntryProxy, self).category.__dict__ return new_inst
编辑:上面的代码片段似乎不适用于django 1.4。
从Django 1.4开始,我像这样手动获取所有值字段:
class EntryProxy(Entry): @property def category(self): category = super(EntryProxy, self).category new_inst = EntryProxy() for attr in [f.attname for f in category.__class__._meta.fields] + ['_state']: setattr(new_inst, attr, getattr(category, attr)) return new_inst
要从查询集切换到子代理类而不打数据库:
class CategoryProxy(Category): @property def entry_set(self): qs = super(CategoryProxy, self).entry_set qs.model = EntryProxy return qs



