Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django model inheritance: create sub-instance of existing instance (downcast)?

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:

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() 

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...

like image 418
Benjamin Wohlwend Avatar asked Oct 31 '10 19:10

Benjamin Wohlwend


1 Answers

This should work:

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

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.

like image 193
Daniel Roseman Avatar answered Oct 14 '22 06:10

Daniel Roseman