Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix #1811: take limit_choices_to into account with FK #6371

Merged
merged 6 commits into from Jan 8, 2019
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
6 changes: 6 additions & 0 deletions rest_framework/relations.py
Expand Up @@ -169,6 +169,12 @@ def get_queryset(self):
# for the field.
# Eg: 'MyRelationship(queryset=ExampleModel.objects.all())'
queryset = queryset.all()
if hasattr(self.parent, "Meta") and hasattr(self.parent.Meta, "model"):
adrienbrunet marked this conversation as resolved.
Show resolved Hide resolved
queryset = queryset.filter(
**self.parent.Meta.model._meta.get_field(
self.source
).get_limit_choices_to()
)
adrienbrunet marked this conversation as resolved.
Show resolved Hide resolved
return queryset

def use_pk_only_optimization(self):
Expand Down
7 changes: 7 additions & 0 deletions tests/models.py
Expand Up @@ -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)
Expand Down
38 changes: 38 additions & 0 deletions 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