|
5 | 5 | from rest_framework import serializers
|
6 | 6 | from rest_framework.exceptions import ErrorDetail
|
7 | 7 | from tests.models import (
|
8 |
| - CustomManagerModel, NullableOneToOneSource, OneToOneTarget |
| 8 | + CustomManagerModel, NullableOneToOneSource, OneToOneTarget, TestListModel |
9 | 9 | )
|
10 | 10 |
|
11 | 11 |
|
@@ -775,3 +775,57 @@ def test(self):
|
775 | 775 | queryset = NullableOneToOneSource.objects.all()
|
776 | 776 | serializer = self.serializer(queryset, many=True)
|
777 | 777 | assert serializer.data
|
| 778 | + |
| 779 | + |
| 780 | +class TestManyTrueValidationCheck: |
| 781 | + """ |
| 782 | + Tests ListSerializer validation with many=True for both valid and invalid model data. |
| 783 | + """ |
| 784 | + |
| 785 | + @pytest.mark.django_db |
| 786 | + def test_run_child_validation_with_many_true(self): |
| 787 | + obj1 = TestListModel.objects.create(name="valid", status="new") |
| 788 | + obj2 = TestListModel.objects.create(name="invalid", status="") |
| 789 | + |
| 790 | + class TestListModelSerializer(serializers.ModelSerializer): |
| 791 | + class Meta: |
| 792 | + model = TestListModel |
| 793 | + fields = ("id", "name", "status") |
| 794 | + |
| 795 | + def validate_status(self, value): |
| 796 | + if value and not self.instance.is_valid: |
| 797 | + return False |
| 798 | + return value |
| 799 | + |
| 800 | + input_data = [ |
| 801 | + {"id": obj1.id, "name": "other", "status": "new"}, |
| 802 | + {"id": obj2.id, "name": "valid", "status": "progress"}, |
| 803 | + ] |
| 804 | + |
| 805 | + serializer = TestListModelSerializer([obj1, obj2], data=input_data, many=True) |
| 806 | + assert serializer.is_valid(), serializer.errors |
| 807 | + |
| 808 | + serializer = TestListModelSerializer(TestListModel.objects.all(), data=input_data, many=True) |
| 809 | + assert serializer.is_valid(), serializer.errors |
| 810 | + |
| 811 | + @pytest.mark.django_db |
| 812 | + def test_validation_error_for_invalid_data(self): |
| 813 | + obj = TestListModel.objects.create(name="valid", status="some-status") |
| 814 | + |
| 815 | + class TestListModelSerializer(serializers.ModelSerializer): |
| 816 | + class Meta: |
| 817 | + model = TestListModel |
| 818 | + fields = ("id", "name", "status") |
| 819 | + |
| 820 | + def validate_status(self, value): |
| 821 | + if value and not self.instance.is_valid: |
| 822 | + return False |
| 823 | + return value |
| 824 | + |
| 825 | + input_data = [ |
| 826 | + {"id": obj.pk, "name": "", "status": -1}, |
| 827 | + ] |
| 828 | + |
| 829 | + serializer = TestListModelSerializer([obj], data=input_data, many=True) |
| 830 | + assert not serializer.is_valid() |
| 831 | + assert "name" in serializer.errors[0] |
0 commit comments