0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

django restframeworkのSerializerのテクニック

Posted at

djangoでrestframeworkを使っていて、リレーションなどの処理に関して
Serializerのテクニックを備忘録として書き残します。随時更新していきたいと思います。

単純なリレーション

例えば従業員モデル(Emproyee)に紐づく部署モデル(Department)を
単純にリレーションする時は下記のように書きます。

class EmproyeeSerializer(serializers.ModelSerializer):
    department = DepartmentSerializer(many=True,read_only=True)#部署をリレーション
    class Meta:
        model = Emproyee
        fields = '__all__'
        read_only_fields = ('user',)

これで、フロントエンド(React)では下記のような感じでリレーションモデルの内容を表示できます。

<p>{emproyee.department.id}<p>
<p>{emproyee.department.name}</p>
//出力結果(例):
13
経理部

Slug(テキスト)でのリレーション

単純なリレーションから発展して、リレーション先のモデルの特定の1つのフィールドを
取り出してメインのモデルのフィールドに追加するような処理もできます。
単純なリレーションでは、従業員モデル(Emproyee)に部署モデル(Department)をオブジェクトで
紐付けていましたが、部署モデルのフィールドの値を従業員モデルのフィールドに追加できます。

class EmproyeeSerializer(serializers.ModelSerializer):
    #部署モデルのフィールドの値をリレーション
    department = serializers.SlugRelatedField(
        read_only=True,
        slug_field='name'#ここでフィールドを指定する
     )
    class Meta:
        model = Emproyee
        fields = '__all__'
        read_only_fields = ('user',)

こうすると、オブジェクトではなく値でリレーションします。
"slug_field="のところでフィールドを指定します。ここは、好きなフィールドに指定可能です。
フロントエンド(React)では下記のような感じでリレーションモデルの内容を表示できます。

<p>{emproyee.department}<p>
//出力結果(例):
経理部

0
0
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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?