Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: Getting a Model type when Using a Defer Query

When you use the defer(...) query command, Django returns a different class than your original model. How can you dynamically get the model's name when using the defer field?

In code:

obj_nodefer = model_class.objects.filter(title="foo")[0]
model_name = str(type(obj_nodefer)) # Works just fine

obj_defer = model_class.objects.filter(title="foo").defer("content")[0]
model_name = str(type(obj_defer)) # Does't return the right name because of defer above.

How do I get the model's name from obj_defer?

like image 425
speedplane Avatar asked Dec 27 '22 11:12

speedplane


1 Answers

On the deferred class, you can also get the original class without manipulating the __class__.__name__ string using:

obj._meta.concrete_model
'product.models.ProductModelName'

obj._meta.concrete_model._meta.app_label
'product'

obj._meta.concrete_model._meta.model_name
'productmodelname'
like image 98
Tina Zhang Avatar answered Jan 04 '23 12:01

Tina Zhang