Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django get list of models in application

So, i have a file models.py in MyApp folder:

from django.db import models class Model_One(models.Model):     ... class Model_Two(models.Model):     ... ... 

It can be about 10-15 classes. How to find all models in the MyApp and get their names?

Since models are not iterable, I don't know if this is even possible.

like image 758
Feanor Avatar asked Jan 02 '12 15:01

Feanor


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.

What is QuerySet?

A QuerySet is a collection of data from a database. A QuerySet is built up as a list of objects. QuerySets makes it easier to get the data you actually need, by allowing you to filter and order the data.

How to save data in models in django?

Creating objectsTo create an object, instantiate it using keyword arguments to the model class, then call save() to save it to the database. This performs an INSERT SQL statement behind the scenes. Django doesn't hit the database until you explicitly call save() . The save() method has no return value.


1 Answers

From Django 1.7 on, you can use this code, for example in your admin.py to register all models:

from django.apps import apps from django.contrib import admin from django.contrib.admin.sites import AlreadyRegistered  app_models = apps.get_app_config('my_app').get_models() for model in app_models:     try:         admin.site.register(model)     except AlreadyRegistered:         pass 
like image 134
Sjoerd Avatar answered Sep 19 '22 01:09

Sjoerd