django: best practice way to get model from an instance of that model
my_model = type(my_instance)
To prove it, you can create another instance:
my_new_instance = type(my_instance)()
This is why there's no direct way of doing it, because python objects already have this feature.
updated...
I liked marcinn's response that uses type(x)
. This is identical to what the original answer used (x.__class__
), but I prefer using functions over accessing magic attribtues. In this manner, I prefer using vars(x)
to x.__dict__
, len(x)
to x.__len__
and so on.
updated 2...
For deferred instances (mentioned by @Cerin in comments) you can access the original class via instance._meta.proxy_for_model
.
my_new_instance = type(my_instance)()