0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[Django] restframeworkのserializerの書き下しをサボる

Posted at

restframeworkを使ってシンプルなCRUDをするサーバーを建てるとき、単純にDBと一対一対応するシリアライザはこのようにすればいちいち書き下さなくて済む。


from django.db import models
from rest_framework import serializers

from my_app.models import Company # 開発するアプリで使うモデル

def _create_vanilla_serializer(
        table_cls: Type[models.Model]) -> Type[serializers.ModelSerializer]:

    def _list_field_names(table_cls):
        return tuple(map(lambda f: f.name, table_cls._meta.fields))

    class VanillaSerializer(serializers.ModelSerializer):
        class Meta:
            model = table_cls
            fields = _list_field_names(table_cls)

    return VanillaSerializer

CompanySerializer = _create_vanilla_serializer(Company)
0
1
0

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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?