DRF: Userを所属グループで検索

django-filters: Userを所属グループで検索 Django REST Frameworkとdjango-filterを使って、Userが所属しているGroupを複数指定して検索することはできます。 以下のように、django-filter.FilterSetを継承したフィルタセットを定義し、filters.ModelMultipleChoiceFilterを使って、Userが所属しているGroupを複数指定することができます。 1 2 3 4 5 6 7 8 9 10 11 12 13 from django.contrib.auth.models import User, Group import django_filters class UserFilter(django_filters.FilterSet): groups = django_filters.ModelMultipleChoiceFilter( field_name='groups__name', to_field_name='name', queryset=Group.objects.all() ) class Meta: model = User fields = ['username', 'groups'] 上記の例では、Userモデルに対するフィルタセットを定義しています。groupsフィールドには、django_filters.ModelMultipleChoiceFilterを使って、Userが所属しているGroupを複数指定することができます。field_nameには、Userモデルのgroups__nameフィールドを指定し、to_field_nameには、Groupモデルのnameフィールドを指定しています。 ...

2023年4月23日 · 1 分

Python: モジュールの実装パス

モジュール名からファイルを見つける Pythonのモジュール名が与えられた時、そのモジュールの実装されているファイルのパスを調べるには、以下のようにします。 1 2 3 4 5 6 7 import importlib.util def get_module_path(module_name): spec = importlib.util.find_spec(module_name) if spec is None: return None return spec.origin 上記のように、importlib.util.find_spec()関数を使って、モジュール名からspecオブジェクトを取得し、spec.origin属性を参照することで、モジュールが実装されているファイルのパスを取得することができます。 ソース: Bing との会話 2023/4/23 (1) 6. モジュール — Python 3.11.3 ドキュメント. https://docs.python.org/ja/3/tutorial/modules.html. (2) Pythonで独自モジュールのディレクトリパスを通す方法 …. https://lightgauge.net/language/python/add-module-path. (3) 【Python】パッケージ・モジュールの検索と import - Qiita. https://qiita.com/shinsa82/items/5004a3ea63594f20190d. Djangoのアプリケーションの場合 1 2 3 4 5 6 7 8 from django.apps import apps class Def: @property def path(self): app_label = self.__module__.split(".")[0] conf = apps.get_app_config(app_label) return conf.path

2023年4月23日 · 1 分

Django: User ログインシグナル

Django: User ログイン ログインシグナル Djangoでログインした時のイベントをシグナルで受け取る方法については、Djangoの公式ドキュメントに詳しく記載されています¹。以下のように、django.contrib.auth.signals.user_logged_inシグナルを使用して、ログイン時に実行する関数を定義し、receiver()デコレーターでシグナルを受信する関数を登録します。 1 2 3 4 5 6 7 from django.contrib.auth.signals import user_logged_in from django.dispatch import receiver @receiver(user_logged_in) def user_logged_in_callback(sender, request, user, **kwargs): # ログイン時に実行する処理 pass このように、シグナルを使用することで、ログイン時に任意の処理を実行することができます。 ソース: Bing との会話 2023/4/21 (1) 「超簡単」Djangoでログインページの実装 - Qiita. https://qiita.com/Yuji-Sakata0110/items/3722fa651e02eafc4d01. (2) 【Django】ログイン・ログアウト機能の実装 - Qiita. https://qiita.com/onishi_820/items/c69ebb6a4e34da0f34d4. (3) Django パスワード試行回数ロックとランダムかつ有効期限付き …. https://qiita.com/startours777/items/5b1fc415e047a2044129.

2023年4月21日 · 1 分

Django: Admin: ManyToManyField Inline (raw_id_fields)

Django: Admin: ManyToManyField Inline (raw_id_fields) raw_id_fields and ManyToMany in Django admin 手順: ManyToManyField を exclude にいれて表示させないようにする Inline Admin を定義する. model には through を定義する 対象モデルフィールドを raw_id_fields に入れる

2023年4月16日 · 1 分

Celery: Singleton Task

Celery: Singleton Tasks SingletonTask 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 from celery.app.task import Task from celery.utils.log import get_task_logger from django.core.cache import cache logger = get_task_logger(__name__) class SingletonTask(Task): def __call__(self, *args, **kwargs): self.lock_key = self.resolve_lock_key(*args, **kwargs) if not self.request.is_eager and self.lock_key: # ロックキーが指定されて、 非同期モードであればシングルトンで動作させる return self.call_singleton(*args, **kwargs) # それ以外はデフォルトの動作 return super().__call__(*args, **kwargs) def resolve_lock_key(self, *args, **kwargs): """ taskに `singleton` キーワード変数でキーが指定されていたらシングルトンモード """ singleton = kwargs.get("singleton", None) return singleton and f"{self.name}-{singleton}" def prepare_execute(self, *args, **kwargs): """ シングルトンタスクの実行の前に何かする""" pass def call_singleton(self, *args, **kwargs): lock = cache.lock(self.lock_key) if not lock.acquire(blocking=False): # 取得できなかったら何もしない(同じような冪等処理がすでに動いている) logger.info("{} failed to lock:".format(self.lock_key)) return "SKIPPED" self.prepare_execute(*args, **kwargs) try: # 実際のタスクを実行 return super(SingletonTask, self).__call__(*args, **kwargs) except Exception as e: logger.error(f"task faiild:{e}") lock.release() raise e finally: lock.release() サンプル 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 class CostSingletonTask(SingletonTask): def prepare_execute(self, *args, **kwargs): """実行前に設定時間(秒)でsleepする この間の重複処理が行われない """ logger.error(f"LOCK ACQUIRE:{self.lock_key}") logger.error(f"CALLING:{args} {kwargs}") logger.info(f"Sleep for ASYNC_WINDOW({settings.ASYNC_WINDOW})") sleep(settings.ASYNC_WINDOW) @shared_task(base=CostSingletonTask) def info(message, singleton=None): logger.error(f"Executing:{message}") return message リンク Celery: Task Singleton? Ensuring a task is only executed one at a time

2023年4月12日 · 1 分

Celery: タスクの結果をMySQLで確認する

Celery: タスクの結果をMySQLで確認する PYPI: django-celery-results = "^2.5.0" settings: 1 2 3 CELERY_RESULT_BACKEND = "django-db" CELERY_RESULT_EXTENDED = True INSTALLED_APPS += ["django_celery_results"] Database Result Backend It seems that you are using Django and Celery to run asynchronous tasks and store the results in a database. One possible reason why the result data is always null is that you are not returning anything from your task function². For example, if your task function looks like this: ...

2023年4月12日 · 3 分

Python: ジョブキューイング

タスクキューシステム Full Stack Python Celery https://docs.celeryq.dev/en/stable/ PYPI: celery redis django-celery-results django-redis Redis: Using Redis poetry add "celery[redis]" djang-celery-results: django-celery-results - Using the Django ORM/Cache as a result backend poetry add django-celery-results Periodic Task: Periodic Tasks 記事: 【Django】CeleryとRedisで非同期処理を実装する方法 DjangoとCeleryを使った非同期処理の結果取得までの流れ 【Python x Django】Djangoによる非同期処理実装(Cerery,Redis) Deploying Django on AWS: Setting up Celery and SQS Celery Task Queue with AWS SQS MySQL:Database returned an invalid datetime value. Are time zone definitions for your database installed? macOS: ...

2023年4月7日 · 1 分

Django: model から DRF ModelSerializer を参照する

modelクラスからシリアライザクラスを参照する models <- api の照合依存のレイアウト 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 partners ├── __init__.py ├── api │ ├── __init__.py │ ├── filters.py │ ├── permissions.py │ ├── schema.py │ ├── serializers.py │ ├── urls.py │ └── viewsets.py ├── apps.py ├── models │ ├── __init__.py │ ├── apimodels.py │ ├── defs.py │ ├── managers.py │ ├── methods.py │ ├── models.py │ └── querysets.py ├── tasks.py └── views.py

2023年4月5日 · 1 分

Django:OpenAPI(Swagger) Scheme を出力して Pydatic クラスを生成できるようにする

DRF: コマンドでShemaを生成する 1 pip install datamodel-code-generator ProfileSerializer(ModelSerializer)から Pydanticモデルを生成する 1 python manage.py generateschema --format openapi-json | jq ".components.schemas.Profile" | datamodel-codegen --output /tmp/model.py

2023年3月24日 · 1 分

Django: asgiref

asgiref https://github.com/django/asgiref ASGI: ASGI is a standard for Python asynchronous web apps and servers to communicate with each other, and positioned as an asynchronous successor to WSGI. You can read more at https://asgi.readthedocs.io/en/latest/ This package includes ASGI base libraries, such as: Sync-to-async and async-to-sync function wrappers, asgiref.sync Server base classes, asgiref.server A WSGI-to-ASGI adapter, in asgiref.wsgi Function wrappers These allow you to wrap or decorate async or sync functions to call them from the other style (so you can call async functions from a synchronous thread, or vice-versa). ...

2021年6月2日 · 3 分