Code

Ticket #19816: ticket19816.diff

File ticket19816.diff, 1.8 KB (added by ethlinn, 14 months ago)

Patch with tests added. Done by me and oinopion.

Line 
1diff --git a/django/db/models/fields/related.py b/django/db/models/fields/related.py
2index bea88ba..01b8a55 100644
3--- a/django/db/models/fields/related.py
4+++ b/django/db/models/fields/related.py
5@@ -904,6 +904,9 @@ class ReverseManyRelatedObjectsDescriptor(object):
6             raise AttributeError("Cannot set values on a ManyToManyField which specifies an intermediary model.  Use %s.%s's Manager instead." % (opts.app_label, opts.object_name))
7 
8         manager = self.__get__(instance)
9+        # clear() can change expected output of 'value' queryset, we force evaluation
10+        # of queryset before clear; ticket #19816
11+        value = tuple(value)
12         manager.clear()
13         manager.add(*value)
14 
15diff --git a/tests/regressiontests/m2m_regress/tests.py b/tests/regressiontests/m2m_regress/tests.py
16index 3dc1d24..90aab5e 100644
17--- a/tests/regressiontests/m2m_regress/tests.py
18+++ b/tests/regressiontests/m2m_regress/tests.py
19@@ -5,7 +5,7 @@ from django.test import TestCase
20 from django.utils import six
21 
22 from .models import (SelfRefer, Tag, TagCollection, Entry, SelfReferChild,
23-    SelfReferChildSibling, Worksheet, RegressionModelSplit)
24+    SelfReferChildSibling, Worksheet, RegressionModelSplit, Line)
25 
26 
27 class M2MRegressionTests(TestCase):
28@@ -96,3 +96,16 @@ class M2MRegressionTests(TestCase):
29         # causes a TypeError in add_lazy_relation
30         m1 = RegressionModelSplit(name='1')
31         m1.save()
32+
33+    def test_m2m_filter(self):
34+        worksheet = Worksheet.objects.create(id=1)
35+        line_hi = Line.objects.create(name="hi")
36+        line_bye = Line.objects.create(name="bye")
37+
38+        worksheet.lines = [line_hi, line_bye]
39+        hi = worksheet.lines.filter(name="hi")
40+
41+        worksheet.lines = hi
42+        self.assertEquals(1, worksheet.lines.count())
43+        self.assertEquals(1, hi.count())
44+