diff --git a/tests/models.py b/tests/models.py index 6aeceb934..55f250e04 100644 --- a/tests/models.py +++ b/tests/models.py @@ -52,6 +52,13 @@ class ForeignKeySource(RESTFrameworkModel): on_delete=models.CASCADE) +class ForeignKeySourceWithLimitedChoices(RESTFrameworkModel): + target = models.ForeignKey(ForeignKeyTarget, help_text='Target', + verbose_name='Target', + limit_choices_to={"name__startswith": "limited-"}, + on_delete=models.CASCADE) + + # Nullable ForeignKey class NullableForeignKeySource(RESTFrameworkModel): name = models.CharField(max_length=100) diff --git a/tests/test_relations_with_limited_queryset.py b/tests/test_relations_with_limited_queryset.py new file mode 100644 index 000000000..4408520d3 --- /dev/null +++ b/tests/test_relations_with_limited_queryset.py @@ -0,0 +1,38 @@ +from django.test import TestCase + +from rest_framework import serializers + +from .models import ( + ForeignKeySource, + ForeignKeyTarget, + ForeignKeySourceWithLimitedChoices, +) + + +class ForeignKeySourceWithLimitedChoicesSerializer(serializers.ModelSerializer): + class Meta: + model = ForeignKeySourceWithLimitedChoices + fields = ("id", "target") + + +class ForeignKeySourceSerializer(serializers.ModelSerializer): + class Meta: + model = ForeignKeySource + fields = ("id", "target") + + +class LimitedChoicesInQuerySetTests(TestCase): + def setUp(self): + for idx in range(1, 4): + limited_target = ForeignKeyTarget(name="limited-target-%d" % idx) + limited_target.save() + target = ForeignKeyTarget(name="target-%d" % idx) + target.save() + + def test_queryset_size_without_limited_choices(self): + queryset = ForeignKeySourceSerializer().fields["target"].get_queryset() + assert len(queryset) == 6 + + def test_queryset_size_with_limited_choices(self): + queryset = ForeignKeySourceWithLimitedChoicesSerializer().fields["target"].get_queryset() + assert len(queryset) == 3