gpt4 book ai didi

python - Django 代理模型和 ForeignKey

转载 作者:太空狗 更新时间:2023-10-29 17:06:10 27 4
gpt4 key购买 nike

如何让entry.category成为CategoryProxy的实例?详情见代码:

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 内部结构以正确复制内部状态...

编辑。原因:我给CategoryProxy添加了方法,想用他:

EntryProxy.objects.get(pk=1).category.method_at_category_proxy()

编辑 2。目前我是这样实现的:

EntryProxy._meta.get_field_by_name('category')[0].rel.to = CategoryProxy

但它看起来很糟糕......

最佳答案

在不访问数据库的情况下从模型类切换到代理类:

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

关于python - Django 代理模型和 ForeignKey,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3891880/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com