Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django : How can I find a list of models that the ORM knows?

In Django, is there a place I can get a list of or look up the models that the ORM knows about?

like image 813
interstar Avatar asked Jul 14 '09 12:07

interstar


People also ask

Is there a list field for Django models?

Mine is simpler to implement, and you can pass a list, dict, or anything that can be converted into json. In Django 1.10 and above, there's a new ArrayField field you can use.

How do I find model in Django?

In Django 1.7+ it is better to use get_model() on the Django app registry, which is available via django. apps. apps. get_model(model_name) .

Where are Django models located?

Since Django only looks for models under the Python path <app>. models , you must declare a relative import in the main models.py file -- for each of the models inside sub-folders -- to make them visible to the app.

What is __ in Django ORM?

In Django, above argument is called field lookups argument, the field lookups argument's format should be fieldname__lookuptype=value. Please note the double underscore ( __ ) between the field name(depe_desc) and lookup type keyword contains.


2 Answers

Simple solution:

import django.apps django.apps.apps.get_models() 

By default apps.get_models() don't include

  • auto-created models for many-to-many relations without an explicit intermediate table
  • models that have been swapped out.

If you want to include these as well,

django.apps.apps.get_models(include_auto_created=True, include_swapped=True) 

Prior to Django 1.7, instead use:

from django.db import models models.get_models(include_auto_created=True) 

The include_auto_created parameter ensures that through tables implicitly created by ManyToManyFields will be retrieved as well.

like image 61
Daniel Roseman Avatar answered Oct 19 '22 15:10

Daniel Roseman


List models using http://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/

from django.contrib.contenttypes.models import ContentType  for ct in ContentType.objects.all():     m = ct.model_class()     print "%s.%s\t%d" % (m.__module__, m.__name__, m._default_manager.count()) 
like image 31
andreipak Avatar answered Oct 19 '22 13:10

andreipak