Django 代理模型和外键 [英] Django proxy model and ForeignKey
问题描述
如何让 entry.category 成为 CategoryProxy 的实例?详情见代码:
How to make entry.category to be instance of CategoryProxy? See code for details:
class Category(models.Model): pass
class Entry(models.Model):
category = models.ForeignKey(Category)
class EntryProxy(Entry):
class Meta:
proxy = True
class CategoryProxy(Category):
class Meta:
proxy = True
entry = EntryProxy.objects.get(pk=1)
entry.category # !!! I want CategoryProxy instance here
从 Category 到 CategoryProxy 的转换也可以,但我对 ORM 内部结构不太熟悉以正确复制内部状态...
Cast from Category to CategoryProxy is ok too, but I am not very familiar with ORM internals to properly copy internal state...
编辑.原因:我给CategoryProxy加了方法,想用他:
EDIT. Reason: I added method to CategoryProxy and want to use him:
EntryProxy.objects.get(pk=1).category.method_at_category_proxy()
编辑 2.目前我是这样实现的:
EntryProxy._meta.get_field_by_name('category')[0].rel.to = CategoryProxy
但它看起来很糟糕...
but it looks terrible...
推荐答案
从模型类切换到代理类而不访问数据库:
To switch from a model class to a proxy class without hitting the database:
class EntryProxy(Entry):
@property
def category(self):
new_inst = EntryProxy()
new_inst.__dict__ = super(EntryProxy, self).category.__dict__
return new_inst
上面的代码片段似乎不适用于 django 1.4.
edit: the snippet above seems not working on django 1.4.
从 django 1.4 开始,我像这样手动获取所有值字段:
Since django 1.4, I take all value fields manually like this:
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
从查询集切换到子代理类而不访问数据库:
To switch from a queryset to a child proxy class without hitting database:
class CategoryProxy(Category):
@property
def entry_set(self):
qs = super(CategoryProxy, self).entry_set
qs.model = EntryProxy
return qs
这篇关于Django 代理模型和外键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!