Django代理模型和ForeignKey [英] Django proxy model and ForeignKey

查看:90
本文介绍了Django代理模型和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

从类别转换为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。
目前我实现了这样:

EDIT 2. Currently I implemented it like this:

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

从一个queryset切换到一个子代理类,而不会触发数据库:

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代理模型和ForeignKey的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆