developer tip

Django는 애플리케이션의 모델 목록을 가져옵니다.

optionbox 2021. 1. 5. 07:57
반응형

Django는 애플리케이션의 모델 목록을 가져옵니다.


그래서 MyApp 폴더에 models.py 파일이 있습니다.

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

약 10-15 수업이 될 수 있습니다. MyApp에서 모든 모델을 찾고 이름을 얻는 방법은 무엇입니까?

모델은 반복 할 수 없기 때문에 이것이 가능한지 모르겠습니다.


최신 정보

최신 버전의 Django는 아래 Sjoerd 답변을 확인하십시오.

2012 년의 원래 답변 : 원하는 작업을 수행하는 가장 좋은 방법입니다.

from django.db.models import get_app, get_models

app = get_app('my_application_name')
for model in get_models(app):
    # do something with the model

이 예에서는 model실제 모델이므로 많은 작업을 수행 할 수 있습니다.

for model in get_models(app):
    new_object = model() # Create an instance of that model
    model.objects.filter(...) # Query the objects of that model
    model._meta.db_table # Get the name of the model in the database
    model._meta.verbose_name # Get a verbose name of the model
    # ...

Django 1.7부터는 모든 모델을 등록하기 위해 admin.py에서이 코드를 사용할 수 있습니다.

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

앱에서 모든 모델을 가져 오는 데 가장 적합한 답변 :

from django.apps import apps
apps.all_models['<app_name>']  #returns dict with all models you defined

대안은 콘텐츠 유형 을 사용하는 것입니다 .

INSTALLED_APPS의 각 애플리케이션에 대한 각 모델은 ContentType 모델의 항목을 가져옵니다. 이를 통해 예를 들어 모델에 대한 외래 키를 가질 수 있습니다.

>>> from django.contrib.contenttypes.models import ContentType
>>> ContentType.objects.filter(app_label="auth")
<QuerySet [<ContentType: group>, <ContentType: permission>, <ContentType: user>]>
>>> [ct.model_class() for ct in ContentType.objects.filter(app_label="auth")]
[<class 'django.contrib.auth.models.Group'>, <class 'django.contrib.auth.models.Permission'>, <class 'django.contrib.auth.models.User'>]

여기에 사용하는 솔루션을 노 코딩 빠른 앤 더러운,의 dumpdata와는 jq:

python manage.py dumpdata oauth2_provider | jq -r '.[] | .model' | uniq

jq원하는 형식을 얻기 위해 명령을 정리할 수도 있습니다 .


보너스 :에 -c플래그를 추가하여 다양한 유형의 개체 수를 볼 수 있습니다 uniq.


이것은 프로젝트의 모든 객체에 대한 설비를 덤프하는 명령을 인쇄합니다. 설정 파일에서 앱 목록을 복사해야합니다. ( apps디렉터리 내에서 앱을 이동했습니다 .)

from django.apps import apps

print(
    '\n'.join(
        [
            '\n'.join(
                [
                    f'PYTHONPATH=.:apps django-admin dumpdata {app}.{model} --settings=my_project.settings > apps/{app}/fixtures/{model}.json'
                    for model in apps.all_models[app]
                ]
            )
            for app in [
                'my_app',
                'my_other_app',
            ]
        ]
    )
)

가상 환경을 활성화했는지 확인하여 올바른 django-admin. (으로 확인하십시오 which django-admin.py.)

Only tangentially related to the original question, but might be useful for someone stumbling across this for the same reason I did. I'm on Django 2.2.4, haven't tested it elsewhere.

ReferenceURL : https://stackoverflow.com/questions/8702772/django-get-list-of-models-in-application

반응형