What Django command(s) must I use to check if model SomeModelName
exists?
exists() to check if a particular instance exists or not. From the . exists() docs: It returns True if the QuerySet contains any results, and False if not.
The __str__ method just tells Django what to print when it needs to print out an instance of the any model.
Is exist in Django? exists() is useful for searches relating to both object membership in a QuerySet and to the existence of any objects in a QuerySet, particularly in the context of a large QuerySet. But ObjectDoesNotExist works only with get() .
Django has an django.apps
module with an apps
class:
from django.apps import apps
this apps
class has a get_models()
function, that returns the Model
classes (these do not include abstract models, and tables as a result of ManyToManyField
s).
We can use .__name__
to obtain the classname. So we can check if SomeModelName
exists with:
from operator import attrgetter
'SomeModelName' in map(attrgetter('__name__'), apps.get_models())
Note that this will specify the name of the classes, and that in the different applications you have registered, several models can have the same name (but these are not the same model).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With