|
6 | 6 |
|
7 | 7 | import pytest |
8 | 8 | from django.db import models |
| 9 | +from django.test import TestCase |
9 | 10 |
|
10 | 11 | from rest_framework import exceptions, fields, relations, serializers |
11 | 12 | from rest_framework.fields import Field |
12 | 13 |
|
13 | 14 | from .models import ( |
14 | | - ForeignKeyTarget, NestedForeignKeySource, NullableForeignKeySource |
| 15 | + ForeignKeyTarget, ManyToManySource, ManyToManyTarget, |
| 16 | + NestedForeignKeySource, NullableForeignKeySource |
15 | 17 | ) |
16 | 18 | from .utils import MockObject |
17 | 19 |
|
@@ -64,6 +66,7 @@ def setup_method(self): |
64 | 66 | class ExampleSerializer(serializers.Serializer): |
65 | 67 | char = serializers.CharField() |
66 | 68 | integer = serializers.IntegerField() |
| 69 | + |
67 | 70 | self.Serializer = ExampleSerializer |
68 | 71 |
|
69 | 72 | def test_valid_serializer(self): |
@@ -774,3 +777,35 @@ def test_nested_key(self): |
774 | 777 | ret = {'a': 1} |
775 | 778 | self.s.set_value(ret, ['x', 'y'], 2) |
776 | 779 | assert ret == {'a': 1, 'x': {'y': 2}} |
| 780 | + |
| 781 | + |
| 782 | +class TestWarningManyToMany(TestCase): |
| 783 | + def test_warning_many_to_many(self): |
| 784 | + """Tests that using a PrimaryKeyRelatedField for a ManyToMany field breaks with default=None.""" |
| 785 | + class ManyToManySourceSerializer(serializers.ModelSerializer): |
| 786 | + targets = serializers.PrimaryKeyRelatedField( |
| 787 | + many=True, |
| 788 | + queryset=ManyToManyTarget.objects.all(), |
| 789 | + default=None |
| 790 | + ) |
| 791 | + |
| 792 | + class Meta: |
| 793 | + model = ManyToManySource |
| 794 | + fields = '__all__' |
| 795 | + |
| 796 | + # Instantiates serializer without 'value' field to force using the default=None for the ManyToMany relation |
| 797 | + serializer = ManyToManySourceSerializer(data={ |
| 798 | + "name": "Invalid Example", |
| 799 | + }) |
| 800 | + |
| 801 | + error_msg = "The field 'targets' on serializer 'ManyToManySourceSerializer' is a ManyToMany field and cannot have a default value of None." |
| 802 | + |
| 803 | + # Calls to get_fields() should raise a ValueError |
| 804 | + with pytest.raises(ValueError) as exc_info: |
| 805 | + serializer.get_fields() |
| 806 | + assert str(exc_info.value) == error_msg |
| 807 | + |
| 808 | + # Calls to is_valid() should behave the same |
| 809 | + with pytest.raises(ValueError) as exc_info: |
| 810 | + serializer.is_valid(raise_exception=True) |
| 811 | + assert str(exc_info.value) == error_msg |
0 commit comments