128👍
✅
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
.
- [Django]-How to call function that takes an argument in a Django template?
- [Django]-Referencing multiple submit buttons in django
- [Django]-Access web server on VirtualBox/Vagrant machine from host browser?
19👍
At least for Django 1.11, this should work (also for deferred instances):
def get_model_for_instance(instance):
return instance._meta.model
- [Django]-Create if doesn't exist
- [Django]-Django get a QuerySet from array of id's in specific order
- [Django]-Why there are two process when i run python manage.py runserver
Source:stackexchange.com