Skip to content

Instantly share code, notes, and snippets.

@nara-l
Last active November 1, 2018 16:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nara-l/f02e31f2d6ee3619f92e4158af5c544c to your computer and use it in GitHub Desktop.
Save nara-l/f02e31f2d6ee3619f92e4158af5c544c to your computer and use it in GitHub Desktop.
How to get a model object from instance in Django
# Sometimes you need to determine a model name from an object, before using
# First long approach may work in every version of Django? not tested
import sys
model_obj # let model_obj be the model object ( instance) from some input
model_name_str = type(model_obj).__name__ # this is model name as string, but we need the object to do the
model_object = getattr(sys.modules[__name__], model_name_str)
# now we can use model object normally
model_object.objects.all() # etc
# Second pythonic approach Works in Django 1.11
# model_obj is the model instance as input from some function
model_object = model_obj._meta.model.objects.all() # with 1 line we can do what we did above
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment