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

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

问题描述

我正在尝试集成一个 3rd 方 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 的模型继承.也就是说,如果您已经创建了用户例如,你不能不在被子下探个究竟instance 对应一个你还没有创建的子类实例.

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.

嗯,我现在需要将这个 3rd 方应用程序与我现有的用户实例集成.那么,如果假设我确实愿意在幕后闲逛,我有什么选择?我知道这行不通:

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 模型继承:创建现有实例的子实例(向下转换)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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