From ba53da894fc713629ae4d3fbdd14eff98c808389 Mon Sep 17 00:00:00 2001 From: Anderson Resende Date: Fri, 8 Jul 2016 20:37:40 -0300 Subject: [PATCH] Fixed #26796 -- Added a system check for m2m fields with ignored limit_choices_to. --- django/db/models/fields/related.py | 9 +++++++ docs/ref/checks.txt | 2 ++ .../test_relative_fields.py | 27 ++++++++++++++----- 3 files changed, 32 insertions(+), 6 deletions(-) diff --git a/django/db/models/fields/related.py b/django/db/models/fields/related.py index d7b61f9a5a..8cc174bdfb 100644 --- a/django/db/models/fields/related.py +++ b/django/db/models/fields/related.py @@ -1228,6 +1228,15 @@ class ManyToManyField(RelatedField): id='fields.W341', ) ) + if self.remote_field.limit_choices_to and self.remote_field.through: + warnings.append( + checks.Warning( + 'limit_choices_to has no effect on ManyToManyField ' + 'with a through model.', + obj=self, + id='fields.W343', + ) + ) return warnings diff --git a/docs/ref/checks.txt b/docs/ref/checks.txt index aff3bd2bdc..5eed9f0aed 100644 --- a/docs/ref/checks.txt +++ b/docs/ref/checks.txt @@ -251,6 +251,8 @@ Related Fields * **fields.W341**: ``ManyToManyField`` does not support ``validators``. * **fields.W342**: Setting ``unique=True`` on a ``ForeignKey`` has the same effect as using a ``OneToOneField``. +* **fields.W343**: ``limit_choices_to`` has no effect on ``ManyToManyField`` + with a ``through`` model. Signals ~~~~~~~ diff --git a/tests/invalid_models_tests/test_relative_fields.py b/tests/invalid_models_tests/test_relative_fields.py index 96d3f7815f..f42d6a5365 100644 --- a/tests/invalid_models_tests/test_relative_fields.py +++ b/tests/invalid_models_tests/test_relative_fields.py @@ -181,7 +181,18 @@ class RelativeFieldTests(SimpleTestCase): name = models.CharField(max_length=20) class ModelM2M(models.Model): - m2m = models.ManyToManyField(Model, null=True, validators=['']) + m2m = models.ManyToManyField( + Model, + null=True, + validators=[''], + limit_choices_to={'name': 'test_name'}, + through='ThroughModel', + through_fields=('modelm2m', 'model'), + ) + + class ThroughModel(models.Model): + model = models.ForeignKey('Model', models.CASCADE) + modelm2m = models.ForeignKey('ModelM2M', models.CASCADE) errors = ModelM2M.check() field = ModelM2M._meta.get_field('m2m') @@ -191,15 +202,19 @@ class RelativeFieldTests(SimpleTestCase): 'null has no effect on ManyToManyField.', obj=field, id='fields.W340', - ) - ] - expected.append( + ), DjangoWarning( 'ManyToManyField does not support validators.', obj=field, id='fields.W341', - ) - ) + ), + DjangoWarning( + 'limit_choices_to has no effect on ManyToManyField ' + 'with a through model.', + obj=field, + id='fields.W343', + ), + ] self.assertEqual(errors, expected)