Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I check if a Model name exists in Django?

What Django command(s) must I use to check if model SomeModelName exists?

like image 622
Username Avatar asked May 31 '18 15:05

Username


People also ask

How do you check if a model exists or not in Django?

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.

What is __ str __ In Django model?

The __str__ method just tells Django what to print when it needs to print out an instance of the any model.

Does exist in Django?

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() .


1 Answers

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 ManyToManyFields).

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).

like image 143
Willem Van Onsem Avatar answered Oct 17 '22 14:10

Willem Van Onsem