[Django]-Django: best practice way to get model from an instance of that model

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.

25👍

my_new_instance = type(my_instance)()

19👍

At least for Django 1.11, this should work (also for deferred instances):

def get_model_for_instance(instance):
    return instance._meta.model

Source here.

Leave a comment