Django模式继承:创建现有实例的子实例(downcast)? [英] Django model inheritance: create sub-instance of existing instance (downcast)?

查看:112
本文介绍了Django模式继承:创建现有实例的子实例(downcast)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试整合一个第三方Django应用程序,这个应用程序使得不幸的决定继承自 django.contrib.auth.models.User ,这是一个很大的 - 不可插入的应用程序。引用 Malcolm Tredinnick

I'm trying to integrate a 3rd party Django app that made the unfortunate decision to inherit from django.contrib.auth.models.User, which is a big no-no for pluggable apps. Quoting Malcolm Tredinnick:


更重要的是,尽管如此,与Python一样,您不能用
Django的模型继承downcast。也就是说,如果您已经创建了用户
实例,那么您不能在封面下填写该
实例对应于尚未创建的子类实例。

More importantly, though, just as in Python you cannot "downcast" with Django's model inheritance. That is, if you've already created the User instance, you cannot, without poking about under the covers, make that instance correspond to a subclass instance that you haven't created yet.

嗯,我处于需要将此第三方应用程序与现有用户实例集成的情况。所以,如果假设我确实愿意在封面下捅,我的选择是什么?我知道这不行:

Well, I'm in the situation where I need to integrate this 3rd party app with my existing user instances. So, if hypothetically I am indeed willing to poke about under the covers, what are my options? I know that this doesn't work:

extended_user = ExtendedUser(user_ptr_id=auth_user.pk)
extended_user.save()

没有例外,但它打破了各种各样的东西,从覆盖所有的列开始 django.contrib.auth.models.User 与空字符串...

There's no exception, but it breaks all kinds of stuff, starting with overwriting all the columns from django.contrib.auth.models.User with empty strings...

推荐答案

这应该可以工作:

extended_user = ExtendedUser(user_ptr_id=auth_user.pk)
extended_user.__dict__.update(auth_user.__dict__)
extended_user.save()

这里你基本上只是复制超出从auth_user版本到extended_user的值,并重新保存。不是很优雅,但它的作品。

Here you're basically just copying over the values from the auth_user version into the extended_user one, and re-saving it. Not very elegant, but it works.

这篇关于Django模式继承:创建现有实例的子实例(downcast)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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