Last active
November 1, 2018 16:38
-
-
Save nara-l/f02e31f2d6ee3619f92e4158af5c544c to your computer and use it in GitHub Desktop.
How to get a model object from instance in Django
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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