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?

More than 1 year has passed since last update.

[Django REST framework] 複合ユニーク制約の実装

Last updated at Posted at 2022-12-17
  1. モデルにconstraintsを付与

    models.py
    from django.db import models
    
    class Book(models.Model):
    
        book_name = models.CharField()
        book_author = models.CharField()
    
        class Meta:
            constraints = [
                models.UniqueConstraint(
                    name='book_unique',
                    fields=[
                        'book_name',
                        'book_author',
                    ]
                )
            ]
    

    これで重複したデータをPOSTすると500エラーが帰ってくる。

    curl -w'%{http_code}\n' -so /dev/null -X 'POST' \
      'http://127.0.0.1:8001/book/' \
      -H 'Content-Type: application/json' \
      -d '{
      "book_name": "TEST",
      "book_author": "TEST",
    }'
    
    # ステータスコードが500で帰ってくる
    500
    

    単一フィールドがユニーク制約の場合だと400が帰ってくるので統一したい場合は下記設定をさらに投入する

  2. シリアライザにUniqueTogetherValidatorを付与

    serializers.py
    from rest_framework import serializers
    from rest_framework.validators import UniqueTogetherValidator
    
    class BookSerializer(serializers.ModelSerializer):
    
        class Meta:
            model = Book
            fields = '__all__'
            validators = [
                UniqueTogetherValidator(
                    queryset=Book.objects.all(),
                    fields=[
                        'book_name',
                        'book_author',
                    ]
                )
            ]
    
    views.py
    from rest_framework import viewsets
    
    class BookViewSet(viewsets.ModelViewSet):
    
        queryset = Book.objects.all()
        serializer_class = serializers.BookSerializer
        filterset_fields = '__all__'
    

    この状態でPOSTするとバリテーションエラー扱いで400を返してくれる。

    curl -w'%{http_code}\n' -so /dev/null -X 'POST' \
      'http://127.0.0.1:8001/book/' \
      -H 'Content-Type: application/json' \
      -d '{
      "book_name": "TEST",
      "book_author": "TEST",
    }'
    
    # ステータスコードが400で帰ってくる
    400
    
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?