LoginSignup
0
2

More than 3 years have passed since last update.

Django: 文字列からクラスをImportする

Last updated at Posted at 2019-11-11

Django 文字列からクラスをImportする。

サンプルのRepositoryはこちらです。
RepositoryはAPPごとのSettingと兼ねているのでご了承ください。

Djangoで文字列からクラスをImportしたいときありますよねー。
そういう時は、django.utils.module_loadingのimport_stringを使います。

from django.utils.module_loading import import_string

cl = import_string('rest_framework.permissions.IsAdminUser')

使い道

自分はPermissionを文字列の配列でsettings.pyに設定し、RestFrameWorkのViewsetで使いたかったときに使用しました。

project/settings.py
SAMPLE_PERMISSIONS = [
    'rest_framework.permissions.IsAuthenticated',
    'sample_app.permissions.SamplePermission'
]
sample_app/views.py
from django.conf import settings
from rest_framework.viewsets import ModelViewSet
from django.utils.module_loading import import_string

from .serializers import SampleSerializer
from .models import Sample


class SampleViewSet(ModelViewSet):
    serializer_class = SampleSerializer
    queryset = Sample.objects.all()

    # ここで使用した。
    # IsAuthenticated, SamplePermissionがPermissionsに適用される。
    permission_classes = [
        import_string(permission_class) for permission_class in settings.SAMPLE_PERMISSIONS]

こんな風に利用できます。
使う時がたまにあると思うので参考に、

サンプルのRepositoryはこちらです。
RepositoryはAPPごとのSettingと兼ねているのでご了承ください。

ではでは、よいDjangoライフを。

0
2
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2