Skip to content

Instantly share code, notes, and snippets.

@kezabelle
Last active December 18, 2015 09:59
Show Gist options
  • Save kezabelle/5765122 to your computer and use it in GitHub Desktop.
Save kezabelle/5765122 to your computer and use it in GitHub Desktop.
Create a model subclass, from a parent superclass, in Django, while using concrete inheritance ... hmmm
class MySuperClass(Model):
# some stuff follows ...
pass
class MySubClass(MySuperClass):
# unique fields
pass
obj = MySuperClass.objects.get(pk=1)
# will potentially error about required fields ...
# in my case, created/modified auto_now fields
subobj = MySubClass.objects.create(mysuperclass_ptr=obj)
# alternative
kwargs = model_to_dict(obj)
# {'id': 1L, 'author': 1L, ... etc}
# errors because model_to_dict is lossy - doesn't get me an auth.User
# instance for the 'author' field, for example ...
subobj = MySubClass.objects.create(mysuperclass_ptr=obj, **kwargs)
# but lol, this works ....
if obj.__class__ != MySubClass:
obj.__class__ = MySubClass
obj.save()
# THX PYTHONS, I GUESS!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment