Dataset Viewer
Auto-converted to Parquet Duplicate
repo
string
instance_id
string
base_commit
string
patch
string
test_patch
string
problem_statement
string
hints_text
string
created_at
string
version
string
FAIL_TO_PASS
string
PASS_TO_PASS
string
environment_setup_commit
string
django/django
django__django-11001
ef082ebb84f00e38af4e8880d04e8365c2766d34
diff --git a/django/db/models/sql/compiler.py b/django/db/models/sql/compiler.py --- a/django/db/models/sql/compiler.py +++ b/django/db/models/sql/compiler.py @@ -32,7 +32,8 @@ def __init__(self, query, connection, using): self.select = None self.annotation_col_map = None self.klass_info = None - self.ordering_parts = re.compile(r'(.*)\s(ASC|DESC)(.*)') + # Multiline ordering SQL clause may appear from RawSQL. + self.ordering_parts = re.compile(r'^(.*)\s(ASC|DESC)(.*)', re.MULTILINE | re.DOTALL) self._meta_ordering = None def setup_query(self):
diff --git a/tests/expressions/tests.py b/tests/expressions/tests.py --- a/tests/expressions/tests.py +++ b/tests/expressions/tests.py @@ -384,6 +384,29 @@ def test_order_by_exists(self): ) self.assertSequenceEqual(mustermanns_by_seniority, [self.max, mary]) + def test_order_by_multiline_sql(self): + raw_order_by = ( + RawSQL(''' + CASE WHEN num_employees > 1000 + THEN num_chairs + ELSE 0 END + ''', []).desc(), + RawSQL(''' + CASE WHEN num_chairs > 1 + THEN 1 + ELSE 0 END + ''', []).asc() + ) + for qs in ( + Company.objects.all(), + Company.objects.distinct(), + ): + with self.subTest(qs=qs): + self.assertSequenceEqual( + qs.order_by(*raw_order_by), + [self.example_inc, self.gmbh, self.foobar_ltd], + ) + def test_outerref(self): inner = Company.objects.filter(point_of_contact=OuterRef('pk')) msg = (
Incorrect removal of order_by clause created as multiline RawSQL Description Hi. The SQLCompiler is ripping off one of my "order by" clause, because he "thinks" the clause was already "seen" (in SQLCompiler.get_order_by()). I'm using expressions written as multiline RawSQLs, which are similar but not the same. The bug is located in SQLCompiler.get_order_by(), somewhere around line computing part of SQL query without ordering: without_ordering = self.ordering_parts.search(sql).group(1) The sql variable contains multiline sql. As a result, the self.ordering_parts regular expression is returning just a line containing ASC or DESC words. This line is added to seen set, and because my raw queries have identical last lines, only the first clasue is returing from SQLCompiler.get_order_by(). As a quick/temporal fix I can suggest making sql variable clean of newline characters, like this: sql_oneline = ' '.join(sql.split('\n')) without_ordering = self.ordering_parts.search(sql_oneline).group(1) Note: beware of unicode (Py2.x u'') and EOL dragons (\r). Example of my query: return MyModel.objects.all().order_by( RawSQL(''' case when status in ('accepted', 'verification') then 2 else 1 end''', []).desc(), RawSQL(''' case when status in ('accepted', 'verification') then (accepted_datetime, preferred_datetime) else null end''', []).asc(), RawSQL(''' case when status not in ('accepted', 'verification') then (accepted_datetime, preferred_datetime, created_at) else null end''', []).desc()) The ordering_parts.search is returing accordingly: ' then 2 else 1 end)' ' else null end' ' else null end' Second RawSQL with a else null end part is removed from query. The fun thing is that the issue can be solved by workaround by adding a space or any other char to the last line. So in case of RawSQL I can just say, that current implementation of avoiding duplicates in order by clause works only for special/rare cases (or does not work in all cases). The bug filed here is about wrong identification of duplicates (because it compares only last line of SQL passed to order by clause). Hope my notes will help you fixing the issue. Sorry for my english.
Is there a reason you can't use ​conditional expressions, e.g. something like: MyModel.objects.annotate( custom_order=Case( When(...), ) ).order_by('custom_order') I'm thinking that would avoid fiddly ordering_parts regular expression. If there's some shortcoming to that approach, it might be easier to address that. Allowing the ordering optimization stuff to handle arbitrary RawSQL may be difficult. Is there a reason you can't use ​conditional expressions No, but I didn't knew about the issue, and writing raw sqls is sometimes faster (not in this case ;) I'm really happy having possibility to mix raw sqls with object queries. Next time I'll use expressions, for sure. Allowing the ordering optimization stuff to handle arbitrary RawSQL may be difficult. Personally I'd like to skip RawSQL clauses in the block which is responsible for finding duplicates. If someone is using raw sqls, he knows the best what he is doing, IMO. And it is quite strange if Django removes silently part of your SQL. This is very confusing. And please note that printing a Query instance was generating incomplete sql, but while checking Query.order_by manually, the return value was containing all clauses. I thought that just printing was affected, but our QA dept told me the truth ;) I know there is no effective way to compare similarity of two raw clauses. This may be hard for expression objects, too, but you have a possibility to implement some __eq__ magic (instead of comparation of generated sqls). Unfortunately I don't know why duplicates detection was implemented, so it's hard to tell how to improve this part. Patches welcome, I suppose. ​PR Is there a reason why you didn't add tests? I was waiting for confirmation, I've added a test. Is it enough? Some additional test coverage needed.
2019-02-17T13:02:09Z
3.0
["test_order_by_multiline_sql (expressions.tests.BasicExpressionsTests)", "test_order_of_operations (expressions.tests.BasicExpressionsTests)"]
["test_deconstruct (expressions.tests.FTests)", "test_deepcopy (expressions.tests.FTests)", "test_equal (expressions.tests.FTests)", "test_hash (expressions.tests.FTests)", "test_not_equal_Value (expressions.tests.FTests)", "test_and (expressions.tests.CombinableTests)", "test_negation (expressions.tests.CombinableTests)", "test_or (expressions.tests.CombinableTests)", "test_reversed_and (expressions.tests.CombinableTests)", "test_reversed_or (expressions.tests.CombinableTests)", "test_aggregates (expressions.tests.ReprTests)", "test_distinct_aggregates (expressions.tests.ReprTests)", "test_expressions (expressions.tests.ReprTests)", "test_filtered_aggregates (expressions.tests.ReprTests)", "test_functions (expressions.tests.ReprTests)", "test_equal (expressions.tests.SimpleExpressionTests)", "test_hash (expressions.tests.SimpleExpressionTests)", "test_month_aggregation (expressions.tests.FieldTransformTests)", "test_multiple_transforms_in_values (expressions.tests.FieldTransformTests)", "test_transform_in_values (expressions.tests.FieldTransformTests)", "test_deconstruct (expressions.tests.ValueTests)", "test_deconstruct_output_field (expressions.tests.ValueTests)", "test_equal (expressions.tests.ValueTests)", "test_equal_output_field (expressions.tests.ValueTests)", "test_hash (expressions.tests.ValueTests)", "test_raise_empty_expressionlist (expressions.tests.ValueTests)", "test_update_TimeField_using_Value (expressions.tests.ValueTests)", "test_update_UUIDField_using_Value (expressions.tests.ValueTests)", "test_complex_expressions (expressions.tests.ExpressionsNumericTests)", "test_fill_with_value_from_same_object (expressions.tests.ExpressionsNumericTests)", "test_filter_not_equals_other_field (expressions.tests.ExpressionsNumericTests)", "test_increment_value (expressions.tests.ExpressionsNumericTests)", "test_F_reuse (expressions.tests.ExpressionsTests)", "test_insensitive_patterns_escape (expressions.tests.ExpressionsTests)", "test_patterns_escape (expressions.tests.ExpressionsTests)", "test_complex_expressions_do_not_introduce_sql_injection_via_untrusted_string_inclusion (expressions.tests.IterableLookupInnerExpressionsTests)", "test_expressions_in_lookups_join_choice (expressions.tests.IterableLookupInnerExpressionsTests)", "test_in_lookup_allows_F_expressions_and_expressions_for_datetimes (expressions.tests.IterableLookupInnerExpressionsTests)", "test_in_lookup_allows_F_expressions_and_expressions_for_integers (expressions.tests.IterableLookupInnerExpressionsTests)", "test_range_lookup_allows_F_expressions_and_expressions_for_integers (expressions.tests.IterableLookupInnerExpressionsTests)", "test_lefthand_addition (expressions.tests.ExpressionOperatorTests)", "test_lefthand_bitwise_and (expressions.tests.ExpressionOperatorTests)", "test_lefthand_bitwise_left_shift_operator (expressions.tests.ExpressionOperatorTests)", "test_lefthand_bitwise_or (expressions.tests.ExpressionOperatorTests)", "test_lefthand_bitwise_right_shift_operator (expressions.tests.ExpressionOperatorTests)", "test_lefthand_division (expressions.tests.ExpressionOperatorTests)", "test_lefthand_modulo (expressions.tests.ExpressionOperatorTests)", "test_lefthand_multiplication (expressions.tests.ExpressionOperatorTests)", "test_lefthand_power (expressions.tests.ExpressionOperatorTests)", "test_lefthand_subtraction (expressions.tests.ExpressionOperatorTests)", "test_right_hand_addition (expressions.tests.ExpressionOperatorTests)", "test_right_hand_division (expressions.tests.ExpressionOperatorTests)", "test_right_hand_modulo (expressions.tests.ExpressionOperatorTests)", "test_right_hand_multiplication (expressions.tests.ExpressionOperatorTests)", "test_right_hand_subtraction (expressions.tests.ExpressionOperatorTests)", "test_righthand_power (expressions.tests.ExpressionOperatorTests)", "test_aggregate_subquery_annotation (expressions.tests.BasicExpressionsTests)", "test_annotate_values_aggregate (expressions.tests.BasicExpressionsTests)", "test_annotate_values_count (expressions.tests.BasicExpressionsTests)", "test_annotate_values_filter (expressions.tests.BasicExpressionsTests)", "test_annotation_with_outerref (expressions.tests.BasicExpressionsTests)", "test_annotations_within_subquery (expressions.tests.BasicExpressionsTests)", "test_arithmetic (expressions.tests.BasicExpressionsTests)", "test_exist_single_field_output_field (expressions.tests.BasicExpressionsTests)", "test_explicit_output_field (expressions.tests.BasicExpressionsTests)", "test_filter_inter_attribute (expressions.tests.BasicExpressionsTests)", "test_filter_with_join (expressions.tests.BasicExpressionsTests)", "test_filtering_on_annotate_that_uses_q (expressions.tests.BasicExpressionsTests)", "test_in_subquery (expressions.tests.BasicExpressionsTests)", "test_incorrect_field_in_F_expression (expressions.tests.BasicExpressionsTests)", "test_incorrect_joined_field_in_F_expression (expressions.tests.BasicExpressionsTests)", "test_nested_subquery (expressions.tests.BasicExpressionsTests)", "test_nested_subquery_outer_ref_2 (expressions.tests.BasicExpressionsTests)", "test_nested_subquery_outer_ref_with_autofield (expressions.tests.BasicExpressionsTests)", "test_new_object_create (expressions.tests.BasicExpressionsTests)", "test_new_object_save (expressions.tests.BasicExpressionsTests)", "test_object_create_with_aggregate (expressions.tests.BasicExpressionsTests)", "test_object_update (expressions.tests.BasicExpressionsTests)", "test_object_update_fk (expressions.tests.BasicExpressionsTests)", "test_object_update_unsaved_objects (expressions.tests.BasicExpressionsTests)", "test_order_by_exists (expressions.tests.BasicExpressionsTests)", "test_outerref (expressions.tests.BasicExpressionsTests)", "test_outerref_mixed_case_table_name (expressions.tests.BasicExpressionsTests)", "test_outerref_with_operator (expressions.tests.BasicExpressionsTests)", "test_parenthesis_priority (expressions.tests.BasicExpressionsTests)", "test_pickle_expression (expressions.tests.BasicExpressionsTests)", "test_subquery (expressions.tests.BasicExpressionsTests)", "test_subquery_filter_by_aggregate (expressions.tests.BasicExpressionsTests)", "test_subquery_references_joined_table_twice (expressions.tests.BasicExpressionsTests)", "test_ticket_11722_iexact_lookup (expressions.tests.BasicExpressionsTests)", "test_ticket_16731_startswith_lookup (expressions.tests.BasicExpressionsTests)", "test_ticket_18375_chained_filters (expressions.tests.BasicExpressionsTests)", "test_ticket_18375_join_reuse (expressions.tests.BasicExpressionsTests)", "test_ticket_18375_kwarg_ordering (expressions.tests.BasicExpressionsTests)", "test_ticket_18375_kwarg_ordering_2 (expressions.tests.BasicExpressionsTests)", "test_update (expressions.tests.BasicExpressionsTests)", "test_update_inherited_field_value (expressions.tests.BasicExpressionsTests)", "test_update_with_fk (expressions.tests.BasicExpressionsTests)", "test_update_with_none (expressions.tests.BasicExpressionsTests)", "test_uuid_pk_subquery (expressions.tests.BasicExpressionsTests)", "test_date_comparison (expressions.tests.FTimeDeltaTests)", "test_date_minus_duration (expressions.tests.FTimeDeltaTests)", "test_date_subtraction (expressions.tests.FTimeDeltaTests)", "test_datetime_subtraction (expressions.tests.FTimeDeltaTests)", "test_datetime_subtraction_microseconds (expressions.tests.FTimeDeltaTests)", "test_delta_add (expressions.tests.FTimeDeltaTests)", "test_delta_subtract (expressions.tests.FTimeDeltaTests)", "test_delta_update (expressions.tests.FTimeDeltaTests)", "test_duration_with_datetime (expressions.tests.FTimeDeltaTests)", "test_duration_with_datetime_microseconds (expressions.tests.FTimeDeltaTests)", "test_durationfield_add (expressions.tests.FTimeDeltaTests)", "test_exclude (expressions.tests.FTimeDeltaTests)", "test_invalid_operator (expressions.tests.FTimeDeltaTests)", "test_mixed_comparisons2 (expressions.tests.FTimeDeltaTests)", "test_multiple_query_compilation (expressions.tests.FTimeDeltaTests)", "test_negative_timedelta_update (expressions.tests.FTimeDeltaTests)", "test_query_clone (expressions.tests.FTimeDeltaTests)", "test_time_subtraction (expressions.tests.FTimeDeltaTests)"]
419a78300f7cd27611196e1e464d50fd0385ff27
django/django
django__django-11999
84633905273fc916e3d17883810d9969c03f73c2
diff --git a/django/db/models/fields/__init__.py b/django/db/models/fields/__init__.py --- a/django/db/models/fields/__init__.py +++ b/django/db/models/fields/__init__.py @@ -763,8 +763,12 @@ def contribute_to_class(self, cls, name, private_only=False): if not getattr(cls, self.attname, None): setattr(cls, self.attname, self.descriptor_class(self)) if self.choices is not None: - setattr(cls, 'get_%s_display' % self.name, - partialmethod(cls._get_FIELD_display, field=self)) + if not hasattr(cls, 'get_%s_display' % self.name): + setattr( + cls, + 'get_%s_display' % self.name, + partialmethod(cls._get_FIELD_display, field=self), + ) def get_filter_kwargs_for_object(self, obj): """
diff --git a/tests/model_fields/tests.py b/tests/model_fields/tests.py --- a/tests/model_fields/tests.py +++ b/tests/model_fields/tests.py @@ -168,6 +168,16 @@ def test_get_FIELD_display_translated(self): self.assertIsInstance(val, str) self.assertEqual(val, 'translated') + def test_overriding_FIELD_display(self): + class FooBar(models.Model): + foo_bar = models.IntegerField(choices=[(1, 'foo'), (2, 'bar')]) + + def get_foo_bar_display(self): + return 'something' + + f = FooBar(foo_bar=1) + self.assertEqual(f.get_foo_bar_display(), 'something') + def test_iterator_choices(self): """ get_choices() works with Iterators.
Cannot override get_FOO_display() in Django 2.2+. Description I cannot override the get_FIELD_display function on models since version 2.2. It works in version 2.1. Example: class FooBar(models.Model): foo_bar = models.CharField(_("foo"), choices=[(1, 'foo'), (2, 'bar')]) def __str__(self): return self.get_foo_bar_display() # This returns 'foo' or 'bar' in 2.2, but 'something' in 2.1 def get_foo_bar_display(self): return "something" What I expect is that I should be able to override this function.
Thanks for this report. Regression in a68ea231012434b522ce45c513d84add516afa60. Reproduced at 54a7b021125d23a248e70ba17bf8b10bc8619234. OK, I have a lead on this. Not at all happy about how it looks at first pass, but I'll a proof of concept PR together for it tomorrow AM. I don't think it should be marked as blocker since it looks like it was never supported, because it depends on the order of attrs passed in ModelBase.__new__(). So on Django 2.1 and Python 3.7: In [1]: import django ...: django.VERSION In [2]: from django.db import models ...: ...: class FooBar(models.Model): ...: def get_foo_bar_display(self): ...: return "something" ...: ...: foo_bar = models.CharField("foo", choices=[(1, 'foo'), (2, 'bar')]) ...: ...: def __str__(self): ...: return self.get_foo_bar_display() # This returns 'foo' or 'bar' in 2.2, but 'something' in 2.1 ...: ...: class Meta: ...: app_label = 'test' ...: ...: FooBar(foo_bar=1) Out[2]: <FooBar: foo> Before ​Python 3.6 the order of attrs wasn't defined at all. Sergey, an example from the ticket description works for me with Django 2.1 and Python 3.6, 3.7 and 3.8. In [2]: import django ...: django.VERSION Out[2]: (2, 1, 13, 'final', 0) In [3]: import sys ...: sys.version Out[3]: '3.5.7 (default, Oct 17 2019, 07:04:41) \n[GCC 8.3.0]' In [4]: from django.db import models ...: ...: class FooBar(models.Model): ...: foo_bar = models.CharField("foo", choices=[(1, 'foo'), (2, 'bar')]) ...: ...: def __str__(self): ...: return self.get_foo_bar_display() # This returns 'foo' or 'bar' in 2.2, but 'something' in 2.1 ...: ...: def get_foo_bar_display(self): ...: return "something" ...: ...: class Meta: ...: app_label = 'test' ...: ...: FooBar(foo_bar=1) Out[4]: <FooBar: foo> OK, so there is a behaviour change here, but Sergey is correct that it does depend on attr order, so it's hard to say that this can be said to ever have been thought of as supported, with the exact example provided. This example produces the opposite result on 2.1 (even on >=PY36): def test_overriding_display_backwards(self): class FooBar2(models.Model): def get_foo_bar_display(self): return "something" foo_bar = models.CharField("foo", choices=[(1, 'foo'), (2, 'bar')]) f = FooBar2(foo_bar=1) # This returns 'foo' or 'bar' in both 2.2 and 2.1 self.assertEqual(f.get_foo_bar_display(), "foo") Because get_foo_bar_display() is defined before foo_bar is gets replaced in the the add_to_class() step. Semantically order shouldn't make a difference. Given that it does, I can't see that we're bound to maintain that behaviour. (There's a possible fix in Field.contribute_to_class() but implementing that just reverses the pass/fail behaviour depending on order...) Rather, the correct way to implement this on 2.2+ is: def test_overriding_display(self): class FooBar(models.Model): foo_bar = models.CharField("foo", choices=[(1, 'foo'), (2, 'bar')]) def _get_FIELD_display(self, field): if field.attname == 'foo_bar': return "something" return super()._get_FIELD_display(field) f = FooBar(foo_bar=1) self.assertEqual(f.get_foo_bar_display(), "something") This is stable for declaration order on version 2.2+. This approach requires overriding _get_FIELD_display() before declaring fields on 2.1, because otherwise Model._get_FIELD_display() is picked up during Field.contribute_to_class(). This ordering dependency is, ultimately, the same issue that was addressed in a68ea231012434b522ce45c513d84add516afa60, and the follow-up in #30254. The behaviour in 2.1 (and before) was incorrect. Yes, there's a behaviour change here but it's a bugfix, and all bugfixes are breaking changes if you're depending on the broken behaviour. I'm going to downgrade this from Release Blocker accordingly. I'll reclassify this as a Documentation issue and provide the working example, as overriding _get_FIELD_display() is a legitimate use-case I'd guess. Replying to Carlton Gibson: (There's a possible fix in Field.contribute_to_class() but implementing that just reverses the pass/fail behaviour depending on order...) Doesn't this fix it? if not hasattr(cls, 'get_%s_display' % self.name): setattr(cls, 'get_%s_display' % self.name, partialmethod(cls._get_FIELD_display, field=self))
2019-10-31T10:39:18Z
3.1
["test_overriding_FIELD_display (model_fields.tests.GetFieldDisplayTests)"]
["test_blank_in_choices (model_fields.tests.GetChoicesTests)", "test_blank_in_grouped_choices (model_fields.tests.GetChoicesTests)", "test_empty_choices (model_fields.tests.GetChoicesTests)", "test_lazy_strings_not_evaluated (model_fields.tests.GetChoicesTests)", "test_check (model_fields.tests.ChoicesTests)", "test_choices (model_fields.tests.ChoicesTests)", "test_flatchoices (model_fields.tests.ChoicesTests)", "test_formfield (model_fields.tests.ChoicesTests)", "test_invalid_choice (model_fields.tests.ChoicesTests)", "Can supply a custom choices form class to Field.formfield()", "deconstruct() uses __qualname__ for nested class support.", "Field instances can be pickled.", "test_field_name (model_fields.tests.BasicFieldTests)", "Fields are ordered based on their creation.", "test_field_repr (model_fields.tests.BasicFieldTests)", "__repr__() uses __qualname__ for nested class support.", "test_field_str (model_fields.tests.BasicFieldTests)", "test_field_verbose_name (model_fields.tests.BasicFieldTests)", "Field.formfield() sets disabled for fields with choices.", "test_show_hidden_initial (model_fields.tests.BasicFieldTests)", "test_choices_and_field_display (model_fields.tests.GetFieldDisplayTests)", "test_empty_iterator_choices (model_fields.tests.GetFieldDisplayTests)", "A translated display value is coerced to str.", "test_iterator_choices (model_fields.tests.GetFieldDisplayTests)", "test_get_choices (model_fields.tests.GetChoicesLimitChoicesToTests)", "test_get_choices_reverse_related_field (model_fields.tests.GetChoicesLimitChoicesToTests)", "test_get_choices (model_fields.tests.GetChoicesOrderingTests)", "test_get_choices_default_ordering (model_fields.tests.GetChoicesOrderingTests)", "test_get_choices_reverse_related_field (model_fields.tests.GetChoicesOrderingTests)", "test_get_choices_reverse_related_field_default_ordering (model_fields.tests.GetChoicesOrderingTests)"]
0668164b4ac93a5be79f5b87fae83c657124d9ab
django/django
django__django-12184
5d674eac871a306405b0fbbaeb17bbeba9c68bf3
diff --git a/django/urls/resolvers.py b/django/urls/resolvers.py --- a/django/urls/resolvers.py +++ b/django/urls/resolvers.py @@ -158,8 +158,9 @@ def match(self, path): # If there are any named groups, use those as kwargs, ignoring # non-named groups. Otherwise, pass all non-named arguments as # positional arguments. - kwargs = {k: v for k, v in match.groupdict().items() if v is not None} + kwargs = match.groupdict() args = () if kwargs else match.groups() + kwargs = {k: v for k, v in kwargs.items() if v is not None} return path[match.end():], args, kwargs return None
diff --git a/tests/urlpatterns/path_urls.py b/tests/urlpatterns/path_urls.py --- a/tests/urlpatterns/path_urls.py +++ b/tests/urlpatterns/path_urls.py @@ -12,6 +12,11 @@ path('included_urls/', include('urlpatterns.included_urls')), re_path(r'^regex/(?P<pk>[0-9]+)/$', views.empty_view, name='regex'), re_path(r'^regex_optional/(?P<arg1>\d+)/(?:(?P<arg2>\d+)/)?', views.empty_view, name='regex_optional'), + re_path( + r'^regex_only_optional/(?:(?P<arg1>\d+)/)?', + views.empty_view, + name='regex_only_optional', + ), path('', include('urlpatterns.more_urls')), path('<lang>/<path:url>/', views.empty_view, name='lang-and-path'), ] diff --git a/tests/urlpatterns/tests.py b/tests/urlpatterns/tests.py --- a/tests/urlpatterns/tests.py +++ b/tests/urlpatterns/tests.py @@ -68,6 +68,16 @@ def test_re_path_with_optional_parameter(self): r'^regex_optional/(?P<arg1>\d+)/(?:(?P<arg2>\d+)/)?', ) + def test_re_path_with_missing_optional_parameter(self): + match = resolve('/regex_only_optional/') + self.assertEqual(match.url_name, 'regex_only_optional') + self.assertEqual(match.kwargs, {}) + self.assertEqual(match.args, ()) + self.assertEqual( + match.route, + r'^regex_only_optional/(?:(?P<arg1>\d+)/)?', + ) + def test_path_lookup_with_inclusion(self): match = resolve('/included_urls/extra/something/') self.assertEqual(match.url_name, 'inner-extra')
Optional URL params crash some view functions. Description My use case, running fine with Django until 2.2: URLConf: urlpatterns += [ ... re_path(r'^module/(?P<format>(html|json|xml))?/?$', views.modules, name='modules'), ] View: def modules(request, format='html'): ... return render(...) With Django 3.0, this is now producing an error: Traceback (most recent call last): File "/l10n/venv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/l10n/venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/l10n/venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) Exception Type: TypeError at /module/ Exception Value: modules() takes from 1 to 2 positional arguments but 3 were given
Tracked regression in 76b993a117b61c41584e95149a67d8a1e9f49dd1. It seems to work if you remove the extra parentheses: re_path(r'^module/(?P<format>html|json|xml)?/?$', views.modules, name='modules'), It seems Django is getting confused by the nested groups.
2019-12-05T13:09:48Z
3.1
["test_re_path_with_missing_optional_parameter (urlpatterns.tests.SimplifiedURLTests)"]
["test_allows_non_ascii_but_valid_identifiers (urlpatterns.tests.ParameterRestrictionTests)", "test_non_identifier_parameter_name_causes_exception (urlpatterns.tests.ParameterRestrictionTests)", "test_matching_urls (urlpatterns.tests.ConverterTests)", "test_nonmatching_urls (urlpatterns.tests.ConverterTests)", "test_resolve_type_error_propagates (urlpatterns.tests.ConversionExceptionTests)", "test_resolve_value_error_means_no_match (urlpatterns.tests.ConversionExceptionTests)", "test_reverse_value_error_propagates (urlpatterns.tests.ConversionExceptionTests)", "test_converter_resolve (urlpatterns.tests.SimplifiedURLTests)", "test_converter_reverse (urlpatterns.tests.SimplifiedURLTests)", "test_converter_reverse_with_second_layer_instance_namespace (urlpatterns.tests.SimplifiedURLTests)", "test_invalid_converter (urlpatterns.tests.SimplifiedURLTests)", "test_path_inclusion_is_matchable (urlpatterns.tests.SimplifiedURLTests)", "test_path_inclusion_is_reversible (urlpatterns.tests.SimplifiedURLTests)", "test_path_lookup_with_double_inclusion (urlpatterns.tests.SimplifiedURLTests)", "test_path_lookup_with_empty_string_inclusion (urlpatterns.tests.SimplifiedURLTests)", "test_path_lookup_with_inclusion (urlpatterns.tests.SimplifiedURLTests)", "test_path_lookup_with_multiple_parameters (urlpatterns.tests.SimplifiedURLTests)", "test_path_lookup_with_typed_parameters (urlpatterns.tests.SimplifiedURLTests)", "test_path_lookup_without_parameters (urlpatterns.tests.SimplifiedURLTests)", "test_path_reverse_with_parameter (urlpatterns.tests.SimplifiedURLTests)", "test_path_reverse_without_parameter (urlpatterns.tests.SimplifiedURLTests)", "test_re_path (urlpatterns.tests.SimplifiedURLTests)", "test_re_path_with_optional_parameter (urlpatterns.tests.SimplifiedURLTests)", "test_space_in_route (urlpatterns.tests.SimplifiedURLTests)", "test_two_variable_at_start_of_path_pattern (urlpatterns.tests.SimplifiedURLTests)"]
0668164b4ac93a5be79f5b87fae83c657124d9ab
django/django
django__django-12113
62254c5202e80a68f4fe6572a2be46a3d953de1a
diff --git a/django/db/backends/sqlite3/creation.py b/django/db/backends/sqlite3/creation.py --- a/django/db/backends/sqlite3/creation.py +++ b/django/db/backends/sqlite3/creation.py @@ -98,4 +98,6 @@ def test_db_signature(self): sig = [self.connection.settings_dict['NAME']] if self.is_in_memory_db(test_database_name): sig.append(self.connection.alias) + else: + sig.append(test_database_name) return tuple(sig)
diff --git a/tests/backends/sqlite/test_creation.py b/tests/backends/sqlite/test_creation.py new file mode 100644 --- /dev/null +++ b/tests/backends/sqlite/test_creation.py @@ -0,0 +1,18 @@ +import copy +import unittest + +from django.db import connection +from django.test import SimpleTestCase + + +@unittest.skipUnless(connection.vendor == 'sqlite', 'SQLite tests') +class TestDbSignatureTests(SimpleTestCase): + def test_custom_test_name(self): + saved_settings = copy.deepcopy(connection.settings_dict) + try: + connection.settings_dict['NAME'] = None + connection.settings_dict['TEST']['NAME'] = 'custom.sqlite.db' + signature = connection.creation.test_db_signature() + self.assertEqual(signature, (None, 'custom.sqlite.db')) + finally: + connection.settings_dict = saved_settings
admin_views.test_multidb fails with persistent test SQLite database. Description (last modified by Mariusz Felisiak) I've tried using persistent SQLite databases for the tests (to make use of --keepdb), but at least some test fails with: sqlite3.OperationalError: database is locked This is not an issue when only using TEST["NAME"] with "default" (which is good enough in terms of performance). diff --git i/tests/test_sqlite.py w/tests/test_sqlite.py index f1b65f7d01..9ce4e32e14 100644 --- i/tests/test_sqlite.py +++ w/tests/test_sqlite.py @@ -15,9 +15,15 @@ DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', + 'TEST': { + 'NAME': 'test_default.sqlite3' + }, }, 'other': { 'ENGINE': 'django.db.backends.sqlite3', + 'TEST': { + 'NAME': 'test_other.sqlite3' + }, } } % tests/runtests.py admin_views.test_multidb -v 3 --keepdb --parallel 1 … Operations to perform: Synchronize unmigrated apps: admin_views, auth, contenttypes, messages, sessions, staticfiles Apply all migrations: admin, sites Running pre-migrate handlers for application contenttypes Running pre-migrate handlers for application auth Running pre-migrate handlers for application sites Running pre-migrate handlers for application sessions Running pre-migrate handlers for application admin Running pre-migrate handlers for application admin_views Synchronizing apps without migrations: Creating tables... Running deferred SQL... Running migrations: No migrations to apply. Running post-migrate handlers for application contenttypes Running post-migrate handlers for application auth Running post-migrate handlers for application sites Running post-migrate handlers for application sessions Running post-migrate handlers for application admin Running post-migrate handlers for application admin_views System check identified no issues (0 silenced). ERROR ====================================================================== ERROR: setUpClass (admin_views.test_multidb.MultiDatabaseTests) ---------------------------------------------------------------------- Traceback (most recent call last): File "…/Vcs/django/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "…/Vcs/django/django/db/backends/sqlite3/base.py", line 391, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: database is locked The above exception was the direct cause of the following exception: Traceback (most recent call last): File "…/Vcs/django/django/test/testcases.py", line 1137, in setUpClass cls.setUpTestData() File "…/Vcs/django/tests/admin_views/test_multidb.py", line 40, in setUpTestData username='admin', password='something', email='test@test.org', File "…/Vcs/django/django/contrib/auth/models.py", line 158, in create_superuser return self._create_user(username, email, password, **extra_fields) File "…/Vcs/django/django/contrib/auth/models.py", line 141, in _create_user user.save(using=self._db) File "…/Vcs/django/django/contrib/auth/base_user.py", line 66, in save super().save(*args, **kwargs) File "…/Vcs/django/django/db/models/base.py", line 741, in save force_update=force_update, update_fields=update_fields) File "…/Vcs/django/django/db/models/base.py", line 779, in save_base force_update, using, update_fields, File "…/Vcs/django/django/db/models/base.py", line 870, in _save_table result = self._do_insert(cls._base_manager, using, fields, update_pk, raw) File "…/Vcs/django/django/db/models/base.py", line 908, in _do_insert using=using, raw=raw) File "…/Vcs/django/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "…/Vcs/django/django/db/models/query.py", line 1175, in _insert return query.get_compiler(using=using).execute_sql(return_id) File "…/Vcs/django/django/db/models/sql/compiler.py", line 1321, in execute_sql cursor.execute(sql, params) File "…/Vcs/django/django/db/backends/utils.py", line 67, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "…/Vcs/django/django/db/backends/utils.py", line 76, in _execute_with_wrappers return executor(sql, params, many, context) File "…/Vcs/django/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "…/Vcs/django/django/db/utils.py", line 89, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "…/Vcs/django/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "…/Vcs/django/django/db/backends/sqlite3/base.py", line 391, in execute return Database.Cursor.execute(self, query, params) django.db.utils.OperationalError: database is locked
This is only an issue when setting TEST["NAME"], but not NAME. The following works: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'django_tests_default.sqlite3', }, 'other': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'django_tests_other.sqlite3', } } Reproduced at 0dd2308cf6f559a4f4b50edd7c005c7cf025d1aa. Created ​PR Hey, I am able to replicate this bug and was able to fix it as well with the help of ​https://github.com/django/django/pull/11678, but the point I am stuck at is how to test it, I am not able to manipulate the cls variable so the next option that is left is create a file like test_sqlite and pass it as a parameter in runtests, should I be doing that? I think we should add tests/backends/sqlite/test_creation.py with regressions tests for test_db_signature(), you can take a look at tests/backends/base/test_creation.py with similar tests.
2019-11-20T17:49:06Z
3.1
["test_custom_test_name (backends.sqlite.test_creation.TestDbSignatureTests)"]
[]
0668164b4ac93a5be79f5b87fae83c657124d9ab
django/django
django__django-11283
08a4ee06510ae45562c228eefbdcaac84bd38c7a
diff --git a/django/contrib/auth/migrations/0011_update_proxy_permissions.py b/django/contrib/auth/migrations/0011_update_proxy_permissions.py --- a/django/contrib/auth/migrations/0011_update_proxy_permissions.py +++ b/django/contrib/auth/migrations/0011_update_proxy_permissions.py @@ -1,5 +1,18 @@ -from django.db import migrations +import sys + +from django.core.management.color import color_style +from django.db import migrations, transaction from django.db.models import Q +from django.db.utils import IntegrityError + +WARNING = """ + A problem arose migrating proxy model permissions for {old} to {new}. + + Permission(s) for {new} already existed. + Codenames Q: {query} + + Ensure to audit ALL permissions for {old} and {new}. +""" def update_proxy_model_permissions(apps, schema_editor, reverse=False): @@ -7,6 +20,7 @@ def update_proxy_model_permissions(apps, schema_editor, reverse=False): Update the content_type of proxy model permissions to use the ContentType of the proxy model. """ + style = color_style() Permission = apps.get_model('auth', 'Permission') ContentType = apps.get_model('contenttypes', 'ContentType') for Model in apps.get_models(): @@ -24,10 +38,16 @@ def update_proxy_model_permissions(apps, schema_editor, reverse=False): proxy_content_type = ContentType.objects.get_for_model(Model, for_concrete_model=False) old_content_type = proxy_content_type if reverse else concrete_content_type new_content_type = concrete_content_type if reverse else proxy_content_type - Permission.objects.filter( - permissions_query, - content_type=old_content_type, - ).update(content_type=new_content_type) + try: + with transaction.atomic(): + Permission.objects.filter( + permissions_query, + content_type=old_content_type, + ).update(content_type=new_content_type) + except IntegrityError: + old = '{}_{}'.format(old_content_type.app_label, old_content_type.model) + new = '{}_{}'.format(new_content_type.app_label, new_content_type.model) + sys.stdout.write(style.WARNING(WARNING.format(old=old, new=new, query=permissions_query))) def revert_proxy_model_permissions(apps, schema_editor):
diff --git a/tests/auth_tests/test_migrations.py b/tests/auth_tests/test_migrations.py --- a/tests/auth_tests/test_migrations.py +++ b/tests/auth_tests/test_migrations.py @@ -4,6 +4,7 @@ from django.contrib.auth.models import Permission, User from django.contrib.contenttypes.models import ContentType from django.test import TestCase +from django.test.utils import captured_stdout from .models import Proxy, UserProxy @@ -152,3 +153,27 @@ def test_user_keeps_same_permissions_after_migrating_backward(self): user = User._default_manager.get(pk=user.pk) for permission in [self.default_permission, self.custom_permission]: self.assertTrue(user.has_perm('auth_tests.' + permission.codename)) + + def test_migrate_with_existing_target_permission(self): + """ + Permissions may already exist: + + - Old workaround was to manually create permissions for proxy models. + - Model may have been concrete and then converted to proxy. + + Output a reminder to audit relevant permissions. + """ + proxy_model_content_type = ContentType.objects.get_for_model(Proxy, for_concrete_model=False) + Permission.objects.create( + content_type=proxy_model_content_type, + codename='add_proxy', + name='Can add proxy', + ) + Permission.objects.create( + content_type=proxy_model_content_type, + codename='display_proxys', + name='May display proxys information', + ) + with captured_stdout() as stdout: + update_proxy_permissions.update_proxy_model_permissions(apps, None) + self.assertIn('A problem arose migrating proxy model permissions', stdout.getvalue())
# Enhanced Problem Statement: Proxy Model Permission Migration Failure ## Issue Description When upgrading a Django project to version 2.2, the migration `auth.0011_update_proxy_permissions` fails with an integrity error when models have been recreated as proxy models. The error occurs because Django attempts to create permission entries in the `auth_permission` table that already exist, violating the unique constraint on `(content_type_id, codename)`. The specific error is: ``` django.db.utils.IntegrityError: duplicate key value violates unique constraint "idx_18141_auth_permission_content_type_id_01ab375a_uniq" DETAIL: Key (content_type_id, codename)=(12, add_agency) already exists. ``` This issue specifically affects proxy models where permissions might have already been created before the model was converted to a proxy model. The migration attempts to create new permissions without properly checking if equivalent permissions already exist in the database. ## Reproduction Steps 1. Create a Django project using Django 2.0 or 2.1. 2. Define a standard model in your application. 3. Run migrations to create the model and its associated permissions. 4. Later, modify the model to be a proxy model (add `class Meta: proxy = True`). 5. Attempt to upgrade to Django 2.2. 6. Run `python manage.py migrate` - the migration will fail at `auth.0011_update_proxy_permissions`. Internally, what happens is: 1. When the model was first created, Django created permission entries in the `auth_permission` table. 2. When the model was converted to a proxy model, new content types may have been created. 3. During the `auth.0011_update_proxy_permissions` migration, Django attempts to create permissions for proxy models. 4. The migration fails to check if equivalent permissions already exist, resulting in an attempt to create duplicate entries. 5. This violates the unique constraint on `(content_type_id, codename)`, causing the integrity error. ## Expected Behavior The migration should successfully complete without integrity errors. It should either: 1. Check for existing permissions before attempting to create new ones for proxy models. 2. Update existing permissions instead of creating new ones when a model has been converted to a proxy model. 3. Skip creating permissions that would violate the unique constraint. ## Exploration Hints ### Files to Examine: - `django/contrib/auth/migrations/0011_update_proxy_permissions.py` - This is the migration file causing the issue, which likely needs to check for existing permissions before creating new ones. - `django/contrib/auth/models.py` - Contains the `Permission` model that defines the unique constraint being violated. - `django/contrib/contenttypes/models.py` - The `ContentType` model and its manager handle how models (including proxy models) are identified in the permission system. - `django/db/migrations/operations/models.py` - Contains migration operations that handle model changes, including permission updates. ### Key Classes/Functions: - `Permission` model - Defines the schema for permissions with a unique constraint on `(content_type, codename)` that's being violated. - `ContentTypeManager.get_for_model()` - Handles retrieving content types for models, with special handling for proxy models via the `for_concrete_model` parameter. - `ContentType.model_class()` - Resolves ContentType objects back to their corresponding model classes. - Migration operations in `auth.0011_update_proxy_permissions` - Need to examine how they handle permission creation for proxy models. ### Areas of Interest: - The unique constraint on `(content_type_id, codename)` in the Permission model that's being violated. - How Django differentiates between original models and their proxy versions when creating permissions. - The caching system for ContentTypes which might retain references to previous model versions. - How the migration identifies which permissions to create for proxy models. ## Fix Hints ### High Confidence Locations: - The `auth.0011_update_proxy_permissions` migration file needs to be modified to check for existing permissions before attempting to create new ones. - The migration should detect when a model has been recreated as a proxy and handle permissions appropriately. ### Implementation Hints: - Before creating new permissions in the migration, query the database to check if permissions with the same codename already exist for the model. - Consider using `get_or_create()` instead of direct creation to avoid duplicate entries. - For proxy models, permissions might need to be transferred or updated rather than created anew. - Consider implementing a deduplication step before attempting to create new permissions. ### Alternative Hypotheses: - The issue could be in the ContentType system's handling of proxy models, which might not properly differentiate between an original model and its proxy version. - Database inconsistencies from previous migrations might exist if models were renamed or modified multiple times. - The way Django generates codenames for permissions might not account for model changes properly. - There could be an issue with how Django associates permissions with proxy models vs. their base models. - Custom permission handling in the user's application might be interfering with Django's built-in permission system.
Please provide a sample project or enough details to reproduce the issue. Same problem for me. If a Permission exists already with the new content_type and permission name, IntegrityError is raised since it violates the unique_key constraint on permission model i.e. content_type_id_code_name To get into the situation where you already have permissions with the content type you should be able to do the following: Start on Django <2.2 Create a model called 'TestModel' Migrate Delete the model called 'TestModel' Add a new proxy model called 'TestModel' Migrate Update to Django >=2.2 Migrate We think this is what happened in our case where we found this issue (​https://sentry.thalia.nu/share/issue/68be0f8c32764dec97855b3cbb3d8b55/). We have a proxy model with the same name that a previous non-proxy model once had. This changed during a refactor and the permissions + content type for the original model still exist. Our solution will probably be removing the existing permissions from the table, but that's really only a workaround. Reproduced with steps from comment. It's probably regression in 181fb60159e54d442d3610f4afba6f066a6dac05. What happens when creating a regular model, deleting it and creating a new proxy model: Create model 'RegularThenProxyModel' +----------------------------------+---------------------------+-----------------------+ | name | codename | model | +----------------------------------+---------------------------+-----------------------+ | Can add regular then proxy model | add_regularthenproxymodel | regularthenproxymodel | +----------------------------------+---------------------------+-----------------------+ Migrate Delete the model called 'RegularThenProxyModel' Add a new proxy model called 'RegularThenProxyModel' +----------------------------------+---------------------------+-----------------------+ | name | codename | model | +----------------------------------+---------------------------+-----------------------+ | Can add concrete model | add_concretemodel | concretemodel | | Can add regular then proxy model | add_regularthenproxymodel | concretemodel | | Can add regular then proxy model | add_regularthenproxymodel | regularthenproxymodel | +----------------------------------+---------------------------+-----------------------+ What happens when creating a proxy model right away: Create a proxy model 'RegularThenProxyModel' +----------------------------------+---------------------------+---------------+ | name | codename | model | +----------------------------------+---------------------------+---------------+ | Can add concrete model | add_concretemodel | concretemodel | | Can add regular then proxy model | add_regularthenproxymodel | concretemodel | +----------------------------------+---------------------------+---------------+ As you can see, the problem here is that permissions are not cleaned up, so we are left with an existing | Can add regular then proxy model | add_regularthenproxymodel | regularthenproxymodel | row. When the 2.2 migration is applied, it tries to create that exact same row, hence the IntegrityError. Unfortunately, there is no remove_stale_permission management command like the one for ContentType. So I think we can do one of the following: Show a nice error message to let the user delete the conflicting migration OR Re-use the existing permission I think 1. is much safer as it will force users to use a new permission and assign it accordingly to users/groups. Edit: I revised my initial comment after reproducing the error in my environment. It's also possible to get this kind of integrity error on the auth.0011 migration if another app is migrated first causing the auth post_migrations hook to run. The auth post migrations hook runs django.contrib.auth.management.create_permissions, which writes the new form of the auth_permission records to the table. Then when the auth.0011 migration runs it tries to update things to the values that were just written. To reproduce this behavior: pip install Django==2.1.7 Create an app, let's call it app, with two models, TestModel(models.Model) and ProxyModel(TestModel) the second one with proxy=True python manage.py makemigrations python manage.py migrate pip install Django==2.2 Add another model to app python manage.py makemigrations migrate the app only, python manage.py migrate app. This does not run the auth migrations, but does run the auth post_migrations hook Note that new records have been added to auth_permission python manage.py migrate, this causes an integrity error when the auth.0011 migration tries to update records that are the same as the ones already added in step 8. This has the same exception as this bug report, I don't know if it's considered a different bug, or the same one. Yes it is the same issue. My recommendation to let the users figure it out with a helpful message still stands even if it may sound a bit painful, because: It prevents data loss (we don't do an automatic delete/create of permissions) It prevents security oversights (we don't re-use an existing permission) It shouldn't happen for most use cases Again, I would love to hear some feedback or other alternatives. I won’t have time to work on this for the next 2 weeks so I’m de-assigning myself. I’ll pick it up again if nobody does and I’m available to discuss feedback/suggestions. I'll make a patch for this. I'll see about raising a suitable warning from the migration but we already warn in the release notes for this to audit permissions: my initial thought was that re-using the permission would be OK. (I see Arthur's comment. Other thoughts?) Being my first contribution I wanted to be super (super) careful with security concerns, but given the existing warning in the release notes for auditing prior to update, I agree that re-using the permission feels pretty safe and would remove overhead for people running into this scenario. Thanks for taking this on Carlton, I'd be happy to review.
2019-04-26T07:02:50Z
3.0
["test_migrate_with_existing_target_permission (auth_tests.test_migrations.ProxyModelWithSameAppLabelTests)"]
["test_migrate_backwards (auth_tests.test_migrations.ProxyModelWithDifferentAppLabelTests)", "test_proxy_model_permissions_contenttype (auth_tests.test_migrations.ProxyModelWithDifferentAppLabelTests)", "test_user_has_now_proxy_model_permissions (auth_tests.test_migrations.ProxyModelWithDifferentAppLabelTests)", "test_user_keeps_same_permissions_after_migrating_backward (auth_tests.test_migrations.ProxyModelWithDifferentAppLabelTests)", "test_migrate_backwards (auth_tests.test_migrations.ProxyModelWithSameAppLabelTests)", "test_proxy_model_permissions_contenttype (auth_tests.test_migrations.ProxyModelWithSameAppLabelTests)", "test_user_keeps_same_permissions_after_migrating_backward (auth_tests.test_migrations.ProxyModelWithSameAppLabelTests)", "test_user_still_has_proxy_model_permissions (auth_tests.test_migrations.ProxyModelWithSameAppLabelTests)"]
419a78300f7cd27611196e1e464d50fd0385ff27
django/django
django__django-11630
65e86948b80262574058a94ccaae3a9b59c3faea
diff --git a/django/core/checks/model_checks.py b/django/core/checks/model_checks.py --- a/django/core/checks/model_checks.py +++ b/django/core/checks/model_checks.py @@ -4,7 +4,8 @@ from itertools import chain from django.apps import apps -from django.core.checks import Error, Tags, register +from django.conf import settings +from django.core.checks import Error, Tags, Warning, register @register(Tags.models) @@ -35,14 +36,25 @@ def check_all_models(app_configs=None, **kwargs): indexes[model_index.name].append(model._meta.label) for model_constraint in model._meta.constraints: constraints[model_constraint.name].append(model._meta.label) + if settings.DATABASE_ROUTERS: + error_class, error_id = Warning, 'models.W035' + error_hint = ( + 'You have configured settings.DATABASE_ROUTERS. Verify that %s ' + 'are correctly routed to separate databases.' + ) + else: + error_class, error_id = Error, 'models.E028' + error_hint = None for db_table, model_labels in db_table_models.items(): if len(model_labels) != 1: + model_labels_str = ', '.join(model_labels) errors.append( - Error( + error_class( "db_table '%s' is used by multiple models: %s." - % (db_table, ', '.join(db_table_models[db_table])), + % (db_table, model_labels_str), obj=db_table, - id='models.E028', + hint=(error_hint % model_labels_str) if error_hint else None, + id=error_id, ) ) for index_name, model_labels in indexes.items():
diff --git a/tests/check_framework/test_model_checks.py b/tests/check_framework/test_model_checks.py --- a/tests/check_framework/test_model_checks.py +++ b/tests/check_framework/test_model_checks.py @@ -1,12 +1,16 @@ from django.core import checks -from django.core.checks import Error +from django.core.checks import Error, Warning from django.db import models from django.test import SimpleTestCase, TestCase, skipUnlessDBFeature from django.test.utils import ( - isolate_apps, modify_settings, override_system_checks, + isolate_apps, modify_settings, override_settings, override_system_checks, ) +class EmptyRouter: + pass + + @isolate_apps('check_framework', attr_name='apps') @override_system_checks([checks.model_checks.check_all_models]) class DuplicateDBTableTests(SimpleTestCase): @@ -28,6 +32,30 @@ class Meta: ) ]) + @override_settings(DATABASE_ROUTERS=['check_framework.test_model_checks.EmptyRouter']) + def test_collision_in_same_app_database_routers_installed(self): + class Model1(models.Model): + class Meta: + db_table = 'test_table' + + class Model2(models.Model): + class Meta: + db_table = 'test_table' + + self.assertEqual(checks.run_checks(app_configs=self.apps.get_app_configs()), [ + Warning( + "db_table 'test_table' is used by multiple models: " + "check_framework.Model1, check_framework.Model2.", + hint=( + 'You have configured settings.DATABASE_ROUTERS. Verify ' + 'that check_framework.Model1, check_framework.Model2 are ' + 'correctly routed to separate databases.' + ), + obj='test_table', + id='models.W035', + ) + ]) + @modify_settings(INSTALLED_APPS={'append': 'basic'}) @isolate_apps('basic', 'check_framework', kwarg_name='apps') def test_collision_across_apps(self, apps): @@ -50,6 +78,34 @@ class Meta: ) ]) + @modify_settings(INSTALLED_APPS={'append': 'basic'}) + @override_settings(DATABASE_ROUTERS=['check_framework.test_model_checks.EmptyRouter']) + @isolate_apps('basic', 'check_framework', kwarg_name='apps') + def test_collision_across_apps_database_routers_installed(self, apps): + class Model1(models.Model): + class Meta: + app_label = 'basic' + db_table = 'test_table' + + class Model2(models.Model): + class Meta: + app_label = 'check_framework' + db_table = 'test_table' + + self.assertEqual(checks.run_checks(app_configs=apps.get_app_configs()), [ + Warning( + "db_table 'test_table' is used by multiple models: " + "basic.Model1, check_framework.Model2.", + hint=( + 'You have configured settings.DATABASE_ROUTERS. Verify ' + 'that basic.Model1, check_framework.Model2 are correctly ' + 'routed to separate databases.' + ), + obj='test_table', + id='models.W035', + ) + ]) + def test_no_collision_for_unmanaged_models(self): class Unmanaged(models.Model): class Meta:
Django throws error when different apps with different models have the same name table name. Description Error message: table_name: (models.E028) db_table 'table_name' is used by multiple models: base.ModelName, app2.ModelName. We have a Base app that points to a central database and that has its own tables. We then have multiple Apps that talk to their own databases. Some share the same table names. We have used this setup for a while, but after upgrading to Django 2.2 we're getting an error saying we're not allowed 2 apps, with 2 different models to have the same table names. Is this correct behavior? We've had to roll back to Django 2.0 for now.
Regression in [5d25804eaf81795c7d457e5a2a9f0b9b0989136c], ticket #20098. My opinion is that as soon as the project has a non-empty DATABASE_ROUTERS setting, the error should be turned into a warning, as it becomes difficult to say for sure that it's an error. And then the project can add the warning in SILENCED_SYSTEM_CHECKS. I agree with your opinion. Assigning to myself, patch on its way Replying to Claude Paroz: Regression in [5d25804eaf81795c7d457e5a2a9f0b9b0989136c], ticket #20098. My opinion is that as soon as the project has a non-empty DATABASE_ROUTERS setting, the error should be turned into a warning, as it becomes difficult to say for sure that it's an error. And then the project can add the warning in SILENCED_SYSTEM_CHECKS.
2019-08-05T11:22:41Z
3.0
["test_collision_across_apps_database_routers_installed (check_framework.test_model_checks.DuplicateDBTableTests)", "test_collision_in_same_app_database_routers_installed (check_framework.test_model_checks.DuplicateDBTableTests)"]
["test_collision_abstract_model (check_framework.test_model_checks.IndexNameTests)", "test_collision_across_apps (check_framework.test_model_checks.IndexNameTests)", "test_collision_in_different_models (check_framework.test_model_checks.IndexNameTests)", "test_collision_in_same_model (check_framework.test_model_checks.IndexNameTests)", "test_no_collision_abstract_model_interpolation (check_framework.test_model_checks.IndexNameTests)", "test_no_collision_across_apps_interpolation (check_framework.test_model_checks.IndexNameTests)", "test_collision_abstract_model (check_framework.test_model_checks.ConstraintNameTests)", "test_collision_across_apps (check_framework.test_model_checks.ConstraintNameTests)", "test_collision_in_different_models (check_framework.test_model_checks.ConstraintNameTests)", "test_collision_in_same_model (check_framework.test_model_checks.ConstraintNameTests)", "test_no_collision_abstract_model_interpolation (check_framework.test_model_checks.ConstraintNameTests)", "test_no_collision_across_apps_interpolation (check_framework.test_model_checks.ConstraintNameTests)", "test_collision_across_apps (check_framework.test_model_checks.DuplicateDBTableTests)", "test_collision_in_same_app (check_framework.test_model_checks.DuplicateDBTableTests)", "test_no_collision_for_proxy_models (check_framework.test_model_checks.DuplicateDBTableTests)", "test_no_collision_for_unmanaged_models (check_framework.test_model_checks.DuplicateDBTableTests)"]
419a78300f7cd27611196e1e464d50fd0385ff27
django/django
django__django-11905
2f72480fbd27896c986c45193e1603e35c0b19a7
diff --git a/django/db/models/lookups.py b/django/db/models/lookups.py --- a/django/db/models/lookups.py +++ b/django/db/models/lookups.py @@ -1,5 +1,6 @@ import itertools import math +import warnings from copy import copy from django.core.exceptions import EmptyResultSet @@ -9,6 +10,7 @@ ) from django.db.models.query_utils import RegisterLookupMixin from django.utils.datastructures import OrderedSet +from django.utils.deprecation import RemovedInDjango40Warning from django.utils.functional import cached_property @@ -463,6 +465,17 @@ class IsNull(BuiltinLookup): prepare_rhs = False def as_sql(self, compiler, connection): + if not isinstance(self.rhs, bool): + # When the deprecation ends, replace with: + # raise ValueError( + # 'The QuerySet value for an isnull lookup must be True or ' + # 'False.' + # ) + warnings.warn( + 'Using a non-boolean value for an isnull lookup is ' + 'deprecated, use True or False instead.', + RemovedInDjango40Warning, + ) sql, params = compiler.compile(self.lhs) if self.rhs: return "%s IS NULL" % sql, params
diff --git a/tests/lookup/models.py b/tests/lookup/models.py --- a/tests/lookup/models.py +++ b/tests/lookup/models.py @@ -96,3 +96,15 @@ class Product(models.Model): class Stock(models.Model): product = models.ForeignKey(Product, models.CASCADE) qty_available = models.DecimalField(max_digits=6, decimal_places=2) + + +class Freebie(models.Model): + gift_product = models.ForeignKey(Product, models.CASCADE) + stock_id = models.IntegerField(blank=True, null=True) + + stock = models.ForeignObject( + Stock, + from_fields=['stock_id', 'gift_product'], + to_fields=['id', 'product'], + on_delete=models.CASCADE, + ) diff --git a/tests/lookup/tests.py b/tests/lookup/tests.py --- a/tests/lookup/tests.py +++ b/tests/lookup/tests.py @@ -9,9 +9,10 @@ from django.db.models.expressions import Exists, OuterRef from django.db.models.functions import Substr from django.test import TestCase, skipUnlessDBFeature +from django.utils.deprecation import RemovedInDjango40Warning from .models import ( - Article, Author, Game, IsNullWithNoneAsRHS, Player, Season, Tag, + Article, Author, Freebie, Game, IsNullWithNoneAsRHS, Player, Season, Tag, ) @@ -969,3 +970,24 @@ def test_exact_query_rhs_with_selected_columns(self): ).values('max_id') authors = Author.objects.filter(id=authors_max_ids[:1]) self.assertEqual(authors.get(), newest_author) + + def test_isnull_non_boolean_value(self): + # These tests will catch ValueError in Django 4.0 when using + # non-boolean values for an isnull lookup becomes forbidden. + # msg = ( + # 'The QuerySet value for an isnull lookup must be True or False.' + # ) + msg = ( + 'Using a non-boolean value for an isnull lookup is deprecated, ' + 'use True or False instead.' + ) + tests = [ + Author.objects.filter(alias__isnull=1), + Article.objects.filter(author__isnull=1), + Season.objects.filter(games__isnull=1), + Freebie.objects.filter(stock__isnull=1), + ] + for qs in tests: + with self.subTest(qs=qs): + with self.assertWarnsMessage(RemovedInDjango40Warning, msg): + qs.exists()
Prevent using __isnull lookup with non-boolean value. Description (last modified by Mariusz Felisiak) __isnull should not allow for non-boolean values. Using truthy/falsey doesn't promote INNER JOIN to an OUTER JOIN but works fine for a simple queries. Using non-boolean values is ​undocumented and untested. IMO we should raise an error for non-boolean values to avoid confusion and for consistency.
PR here: ​https://github.com/django/django/pull/11873 After the reconsideration I don't think that we should change this ​documented behavior (that is in Django from the very beginning). __isnull lookup expects boolean values in many places and IMO it would be confusing if we'll allow for truthy/falsy values, e.g. take a look at these examples field__isnull='false' or field__isnull='true' (both would return the same result). You can always call bool() on a right hand side. Sorry for my previous acceptation (I shouldn't triage tickets in the weekend). Replying to felixxm: After the reconsideration I don't think that we should change this ​documented behavior (that is in Django from the very beginning). __isnull lookup expects boolean values in many places and IMO it would be confusing if we'll allow for truthy/falsy values, e.g. take a look at these examples field__isnull='false' or field__isnull='true' (both would return the same result). You can always call bool() on a right hand side. Sorry for my previous acceptation (I shouldn't triage tickets in the weekend). I understand your point. But is there anything we can do to avoid people falling for the same pitfall I did? The problem, in my opinion, is that it works fine for simple queries but as soon as you add a join that needs promotion it will break, silently. Maybe we should make it raise an exception when a non-boolean is passed? One valid example is to have a class that implements __bool__. You can see here ​https://github.com/django/django/blob/d9881a025c15d87b2a7883ee50771117450ea90d/django/db/models/lookups.py#L465-L470 that non-bool value is converted to IS NULL and IS NOT NULL already using the truthy/falsy values. IMO it would be confusing if we'll allow for truthy/falsy values, e.g. take a look at these examples fieldisnull='false' or fieldisnull='true' (both would return the same result). This is already the case. It just is inconsistent, in lookups.py field__isnull='false' will be a positive condition but on the query.py it will be the negative condition. Maybe adding a note on the documentation? something like: "Although it might seem like it will work with non-bool fields, this is not supported and can lead to inconsistent behaviours" Agreed, we should raise an error for non-boolean values, e.g. diff --git a/django/db/models/lookups.py b/django/db/models/lookups.py index 9344979c56..fc4a38c4fe 100644 --- a/django/db/models/lookups.py +++ b/django/db/models/lookups.py @@ -463,6 +463,11 @@ class IsNull(BuiltinLookup): prepare_rhs = False def as_sql(self, compiler, connection): + if not isinstance(self.rhs, bool): + raise ValueError( + 'The QuerySet value for an isnull lookup must be True or ' + 'False.' + ) sql, params = compiler.compile(self.lhs) if self.rhs: return "%s IS NULL" % sql, params I changed the ticket description. Thanks, I'll work on it! Wouldn't that possibly break backward compatibility? I'm not familiar with how Django moves in that regard. We can add a release note in "Backwards incompatible changes" or deprecate this and remove in Django 4.0. I have to thing about it, please give me a day, maybe I will change my mind :) No problem. Thanks for taking the time to look into this! Another interesting example related to this: As an anecdote, I've also got bitten by this possibility. An attempt to write WHERE (field IS NULL) = boolean_field as .filter(field__isnull=F('boolean_field')) didn't go as I expected. Alexandr Aktsipetrov -- ​https://groups.google.com/forum/#!msg/django-developers/AhY2b3rxkfA/0sz3hNanCgAJ This example will generate the WHERE .... IS NULL. I guess we also would want an exception thrown here. André, IMO we should deprecate using non-boolean values in Django 3.1 (RemovedInDjango40Warning) and remove in Django 4.0 (even if it is untested and undocumented). I can imagine that a lot of people use e.g. 1 and 0 instead of booleans. Attached diff fixes also issue with passing a F() expression. def as_sql(self, compiler, connection): if not isinstance(self.rhs, bool): raise RemovedInDjango40Warning(...) .... Replying to felixxm: André, IMO we should deprecate using non-boolean values in Django 3.1 (RemovedInDjango40Warning) and remove in Django 4.0 (even if it is untested and undocumented). I can imagine that a lot of people use e.g. 1 and 0 instead of booleans. Attached diff fixes also issue with passing a F() expression. def as_sql(self, compiler, connection): if not isinstance(self.rhs, bool): raise RemovedInDjango40Warning(...) .... Sound like a good plan. Not super familiar with the branch structure of Django. So, I guess the path to follow is to make a PR to master adding the deprecation warning and eventually when master is 4.x we create the PR raising the ValueError. Is that right? Thanks! André, yes mostly. You can find more details about that ​from the documentation.
2019-10-11T18:19:39Z
3.1
["test_isnull_non_boolean_value (lookup.tests.LookupTests)", "test_iterator (lookup.tests.LookupTests)"]
["test_chain_date_time_lookups (lookup.tests.LookupTests)", "test_count (lookup.tests.LookupTests)", "test_custom_field_none_rhs (lookup.tests.LookupTests)", "Lookup.can_use_none_as_rhs=True allows None as a lookup value.", "test_error_messages (lookup.tests.LookupTests)", "test_escaping (lookup.tests.LookupTests)", "test_exact_exists (lookup.tests.LookupTests)", "Transforms are used for __exact=None.", "test_exact_query_rhs_with_selected_columns (lookup.tests.LookupTests)", "test_exact_sliced_queryset_limit_one (lookup.tests.LookupTests)", "test_exact_sliced_queryset_limit_one_offset (lookup.tests.LookupTests)", "test_exact_sliced_queryset_not_limited_to_one (lookup.tests.LookupTests)", "test_exclude (lookup.tests.LookupTests)", "test_exists (lookup.tests.LookupTests)", "test_get_next_previous_by (lookup.tests.LookupTests)", "test_in (lookup.tests.LookupTests)", "test_in_bulk (lookup.tests.LookupTests)", "test_in_bulk_lots_of_ids (lookup.tests.LookupTests)", "test_in_bulk_non_unique_field (lookup.tests.LookupTests)", "test_in_bulk_with_field (lookup.tests.LookupTests)", "test_in_different_database (lookup.tests.LookupTests)", "test_in_keeps_value_ordering (lookup.tests.LookupTests)", "test_lookup_collision (lookup.tests.LookupTests)", "test_lookup_date_as_str (lookup.tests.LookupTests)", "test_lookup_int_as_str (lookup.tests.LookupTests)", "test_nested_outerref_lhs (lookup.tests.LookupTests)", "test_none (lookup.tests.LookupTests)", "test_nonfield_lookups (lookup.tests.LookupTests)", "test_pattern_lookups_with_substr (lookup.tests.LookupTests)", "test_regex (lookup.tests.LookupTests)", "test_regex_backreferencing (lookup.tests.LookupTests)", "test_regex_non_ascii (lookup.tests.LookupTests)", "test_regex_non_string (lookup.tests.LookupTests)", "test_regex_null (lookup.tests.LookupTests)", "test_relation_nested_lookup_error (lookup.tests.LookupTests)", "test_unsupported_lookups (lookup.tests.LookupTests)", "test_values (lookup.tests.LookupTests)", "test_values_list (lookup.tests.LookupTests)"]
0668164b4ac93a5be79f5b87fae83c657124d9ab
django/django
django__django-11742
fee75d2aed4e58ada6567c464cfd22e89dc65f4a
diff --git a/django/db/models/fields/__init__.py b/django/db/models/fields/__init__.py --- a/django/db/models/fields/__init__.py +++ b/django/db/models/fields/__init__.py @@ -257,6 +257,7 @@ def is_value(value, accept_promise=True): ) ] + choice_max_length = 0 # Expect [group_name, [value, display]] for choices_group in self.choices: try: @@ -270,16 +271,32 @@ def is_value(value, accept_promise=True): for value, human_name in group_choices ): break + if self.max_length is not None and group_choices: + choice_max_length = max( + choice_max_length, + *(len(value) for value, _ in group_choices if isinstance(value, str)), + ) except (TypeError, ValueError): # No groups, choices in the form [value, display] value, human_name = group_name, group_choices if not is_value(value) or not is_value(human_name): break + if self.max_length is not None and isinstance(value, str): + choice_max_length = max(choice_max_length, len(value)) # Special case: choices=['ab'] if isinstance(choices_group, str): break else: + if self.max_length is not None and choice_max_length > self.max_length: + return [ + checks.Error( + "'max_length' is too small to fit the longest value " + "in 'choices' (%d characters)." % choice_max_length, + obj=self, + id='fields.E009', + ), + ] return [] return [
diff --git a/tests/invalid_models_tests/test_ordinary_fields.py b/tests/invalid_models_tests/test_ordinary_fields.py --- a/tests/invalid_models_tests/test_ordinary_fields.py +++ b/tests/invalid_models_tests/test_ordinary_fields.py @@ -304,6 +304,32 @@ class Model(models.Model): self.assertEqual(Model._meta.get_field('field').check(), []) + def test_choices_in_max_length(self): + class Model(models.Model): + field = models.CharField( + max_length=2, choices=[ + ('ABC', 'Value Too Long!'), ('OK', 'Good') + ], + ) + group = models.CharField( + max_length=2, choices=[ + ('Nested', [('OK', 'Good'), ('Longer', 'Longer')]), + ('Grouped', [('Bad', 'Bad')]), + ], + ) + + for name, choice_max_length in (('field', 3), ('group', 6)): + with self.subTest(name): + field = Model._meta.get_field(name) + self.assertEqual(field.check(), [ + Error( + "'max_length' is too small to fit the longest value " + "in 'choices' (%d characters)." % choice_max_length, + obj=field, + id='fields.E009', + ), + ]) + def test_bad_db_index_value(self): class Model(models.Model): field = models.CharField(max_length=10, db_index='bad')
Add check to ensure max_length fits longest choice. Description There is currently no check to ensure that Field.max_length is large enough to fit the longest value in Field.choices. This would be very helpful as often this mistake is not noticed until an attempt is made to save a record with those values that are too long.
2019-09-04T08:30:14Z
3.0
["test_choices_in_max_length (invalid_models_tests.test_ordinary_fields.CharFieldTests)", "test_choices_named_group (invalid_models_tests.test_ordinary_fields.CharFieldTests)"]
["test_non_nullable_blank (invalid_models_tests.test_ordinary_fields.GenericIPAddressFieldTests)", "test_forbidden_files_and_folders (invalid_models_tests.test_ordinary_fields.FilePathFieldTests)", "test_max_length_warning (invalid_models_tests.test_ordinary_fields.IntegerFieldTests)", "test_primary_key (invalid_models_tests.test_ordinary_fields.FileFieldTests)", "test_upload_to_callable_not_checked (invalid_models_tests.test_ordinary_fields.FileFieldTests)", "test_upload_to_starts_with_slash (invalid_models_tests.test_ordinary_fields.FileFieldTests)", "test_valid_case (invalid_models_tests.test_ordinary_fields.FileFieldTests)", "test_valid_default_case (invalid_models_tests.test_ordinary_fields.FileFieldTests)", "test_str_default_value (invalid_models_tests.test_ordinary_fields.BinaryFieldTests)", "test_valid_default_value (invalid_models_tests.test_ordinary_fields.BinaryFieldTests)", "test_max_length_warning (invalid_models_tests.test_ordinary_fields.AutoFieldTests)", "test_primary_key (invalid_models_tests.test_ordinary_fields.AutoFieldTests)", "test_valid_case (invalid_models_tests.test_ordinary_fields.AutoFieldTests)", "test_fix_default_value (invalid_models_tests.test_ordinary_fields.DateTimeFieldTests)", "test_fix_default_value_tz (invalid_models_tests.test_ordinary_fields.DateTimeFieldTests)", "test_auto_now_and_auto_now_add_raise_error (invalid_models_tests.test_ordinary_fields.DateFieldTests)", "test_fix_default_value (invalid_models_tests.test_ordinary_fields.DateFieldTests)", "test_fix_default_value_tz (invalid_models_tests.test_ordinary_fields.DateFieldTests)", "test_fix_default_value (invalid_models_tests.test_ordinary_fields.TimeFieldTests)", "test_fix_default_value_tz (invalid_models_tests.test_ordinary_fields.TimeFieldTests)", "test_bad_values_of_max_digits_and_decimal_places (invalid_models_tests.test_ordinary_fields.DecimalFieldTests)", "test_decimal_places_greater_than_max_digits (invalid_models_tests.test_ordinary_fields.DecimalFieldTests)", "test_negative_max_digits_and_decimal_places (invalid_models_tests.test_ordinary_fields.DecimalFieldTests)", "test_required_attributes (invalid_models_tests.test_ordinary_fields.DecimalFieldTests)", "test_valid_field (invalid_models_tests.test_ordinary_fields.DecimalFieldTests)", "test_bad_db_index_value (invalid_models_tests.test_ordinary_fields.CharFieldTests)", "test_bad_max_length_value (invalid_models_tests.test_ordinary_fields.CharFieldTests)", "test_bad_validators (invalid_models_tests.test_ordinary_fields.CharFieldTests)", "test_choices_containing_lazy (invalid_models_tests.test_ordinary_fields.CharFieldTests)", "test_choices_containing_non_pairs (invalid_models_tests.test_ordinary_fields.CharFieldTests)", "test_choices_named_group_bad_structure (invalid_models_tests.test_ordinary_fields.CharFieldTests)", "test_choices_named_group_lazy (invalid_models_tests.test_ordinary_fields.CharFieldTests)", "test_choices_named_group_non_pairs (invalid_models_tests.test_ordinary_fields.CharFieldTests)", "test_iterable_of_iterable_choices (invalid_models_tests.test_ordinary_fields.CharFieldTests)", "test_lazy_choices (invalid_models_tests.test_ordinary_fields.CharFieldTests)", "test_missing_max_length (invalid_models_tests.test_ordinary_fields.CharFieldTests)", "test_negative_max_length (invalid_models_tests.test_ordinary_fields.CharFieldTests)", "test_non_iterable_choices (invalid_models_tests.test_ordinary_fields.CharFieldTests)", "Two letters isn't a valid choice pair.", "test_str_max_length_type (invalid_models_tests.test_ordinary_fields.CharFieldTests)", "test_str_max_length_value (invalid_models_tests.test_ordinary_fields.CharFieldTests)", "test_valid_field (invalid_models_tests.test_ordinary_fields.CharFieldTests)", "test_pillow_installed (invalid_models_tests.test_ordinary_fields.ImageFieldTests)"]
419a78300f7cd27611196e1e464d50fd0385ff27
django/django
django__django-11910
d232fd76a85870daf345fd8f8d617fe7802ae194
diff --git a/django/db/migrations/autodetector.py b/django/db/migrations/autodetector.py --- a/django/db/migrations/autodetector.py +++ b/django/db/migrations/autodetector.py @@ -927,6 +927,10 @@ def generate_altered_fields(self): if remote_field_name: to_field_rename_key = rename_key + (remote_field_name,) if to_field_rename_key in self.renamed_fields: + # Repoint both model and field name because to_field + # inclusion in ForeignKey.deconstruct() is based on + # both. + new_field.remote_field.model = old_field.remote_field.model new_field.remote_field.field_name = old_field.remote_field.field_name # Handle ForeignObjects which can have multiple from_fields/to_fields. from_fields = getattr(new_field, 'from_fields', None)
diff --git a/tests/migrations/test_autodetector.py b/tests/migrations/test_autodetector.py --- a/tests/migrations/test_autodetector.py +++ b/tests/migrations/test_autodetector.py @@ -932,6 +932,30 @@ def test_rename_foreign_object_fields(self): changes, 'app', 0, 1, model_name='bar', old_name='second', new_name='second_renamed', ) + def test_rename_referenced_primary_key(self): + before = [ + ModelState('app', 'Foo', [ + ('id', models.CharField(primary_key=True, serialize=False)), + ]), + ModelState('app', 'Bar', [ + ('id', models.AutoField(primary_key=True)), + ('foo', models.ForeignKey('app.Foo', models.CASCADE)), + ]), + ] + after = [ + ModelState('app', 'Foo', [ + ('renamed_id', models.CharField(primary_key=True, serialize=False)) + ]), + ModelState('app', 'Bar', [ + ('id', models.AutoField(primary_key=True)), + ('foo', models.ForeignKey('app.Foo', models.CASCADE)), + ]), + ] + changes = self.get_changes(before, after, MigrationQuestioner({'ask_rename': True})) + self.assertNumberMigrations(changes, 'app', 1) + self.assertOperationTypes(changes, 'app', 0, ['RenameField']) + self.assertOperationAttributes(changes, 'app', 0, 0, old_name='id', new_name='renamed_id') + def test_rename_field_preserved_db_column(self): """ RenameField is used if a field is renamed and db_column equal to the
# ForeignKey `to_field` Not Updated When Renaming PrimaryKey Fields ## Issue Description When renaming a field that serves as a primary key using Django's migration system, foreign keys that explicitly reference this field via the `to_field` parameter continue to point to the old field name rather than updating to the new field name. This creates a disconnect between the model definition and the database schema, where the foreign key's `to_field` parameter contains a reference to a field name that no longer exists in the target model. This issue specifically occurs during the migration process when a `RenameField` operation is applied to a primary key field that is referenced by foreign keys from other models. ## Reproduction Steps ```python # Initial model definitions class ModelA(models.Model): field_wrong = models.CharField('field1', max_length=50, primary_key=True) class ModelB(models.Model): field_fk = models.ForeignKey(ModelA, blank=True, null=True, on_delete=models.CASCADE) # Apply initial migrations... # Modified model with renamed primary key class ModelA(models.Model): field_fixed = models.CharField('field1', max_length=50, primary_key=True) # Renamed from field_wrong class ModelB(models.Model): field_fk = models.ForeignKey(ModelA, blank=True, null=True, on_delete=models.CASCADE) # Generate migrations... ``` The resulting migration will correctly include a `RenameField` operation for ModelA's primary key, but any foreign keys pointing to this field will still reference `field_wrong` instead of `field_fixed` in their `to_field` parameter. This happens because: 1. Django's migration framework detects the field rename and generates a `RenameField` operation. 2. However, it fails to update references to this field in other models' foreign keys. 3. The `to_field` parameter in foreign keys is stored as a string literal in the migration files. 4. When migrations are applied, the foreign key still references a non-existent field name. ## Expected Behavior When a field that serves as a primary key is renamed, all foreign keys that reference it via `to_field` should be automatically updated to point to the new field name. The migration system should detect these dependencies and update all relevant references to maintain referential integrity. ## Exploration Hints ### Files to Examine: - **django/db/migrations/autodetector.py** - This file contains the `MigrationAutodetector` class which is responsible for detecting model changes and generating appropriate migration operations. The issue likely stems from this component not properly tracking field renames across model relationships. - **django/db/migrations/operations/fields.py** - Contains the `RenameField` operation class, which handles field renaming but appears to be missing logic to update references to the renamed field in other models. - **django/db/migrations/state.py** - Manages the `ProjectState` and `ModelState` classes that track the state of models during migration operations. The issue may involve how renamed fields are tracked in the state representation. - **django/db/models/fields/related.py** - Contains the `ForeignKey` class implementation, which stores and manages the `to_field` parameter. - **django/db/models/options.py** - Manages model metadata through the `Options` class, including field tracking and relationships. ### Key Classes/Functions: - **MigrationAutodetector._detect_field_renames()** - Responsible for detecting renamed fields; should analyze how it handles dependencies when primary keys are renamed. - **RenameField.state_forwards()** - Updates the Django model state when a field is renamed but doesn't appear to update references across models. - **ForeignKey.__init__() and ForeignKey.deconstruct()** - These methods handle how the `to_field` parameter is processed and serialized for migrations. - **ModelState.clone() and ModelState.rename_field()** - Handle field renaming in the model state but may not properly propagate changes to related models. ### Areas of Interest: - How Django's migration system tracks dependencies between models, especially with respect to field renames and foreign key references - The serialization and deserialization of `to_field` parameters in foreign keys during migration generation - How field references are tracked and updated across models when fields are renamed - The interaction between explicit `to_field` references and Django's default behavior of referencing primary keys ## Fix Hints ### High Confidence Locations: - **MigrationAutodetector._detect_changes()** or **_detect_field_renames()** - The fix likely involves modifying how field renames are detected and ensuring that foreign key references are updated accordingly. - **RenameField.state_forwards()** - This method needs to be enhanced to scan all models in the state for foreign keys referencing the renamed field and update their `to_field` parameters. ### Implementation Hints: - Add logic to the `RenameField` operation to track which primary key fields are being renamed. - When a primary key is renamed, scan all models in the project state for foreign keys referencing the renamed model. - For each foreign key found, check if its `to_field` parameter references the old field name and update it to the new name. - Ensure that this update happens in the same transaction as the field rename to maintain database integrity. - Consider adding a validation step that warns users about potentially broken foreign key references after field renames. ### Alternative Hypotheses: 1. The issue might involve how Django's ORM resolves field names at runtime versus how they're stored in migration files. There could be a disconnect between these two layers. 2. The problem might be related to the migration dependency resolution system, which might not correctly identify that foreign key references need to be updated when their target fields are renamed. 3. This could be an edge case specifically affecting primary keys that are explicitly referenced via `to_field`, as Django normally defaults to using the primary key without explicitly naming it. 4. There may be issues with how the model state is cached and refreshed during the migration detection process, causing outdated references to persist.
Thanks for this ticket. It looks like a regression in dcdd219ee1e062dc6189f382e0298e0adf5d5ddf, because an AlterField operation wasn't generated in such cases before this change (and I don't think we need it).
2019-10-14T01:56:49Z
3.1
["test_rename_referenced_primary_key (migrations.test_autodetector.AutodetectorTests)"]
["test_add_alter_order_with_respect_to (migrations.test_autodetector.AutodetectorTests)", "test_add_blank_textfield_and_charfield (migrations.test_autodetector.AutodetectorTests)", "Test change detection of new constraints.", "test_add_date_fields_with_auto_now_add_asking_for_default (migrations.test_autodetector.AutodetectorTests)", "test_add_date_fields_with_auto_now_add_not_asking_for_null_addition (migrations.test_autodetector.AutodetectorTests)", "test_add_date_fields_with_auto_now_not_asking_for_default (migrations.test_autodetector.AutodetectorTests)", "Tests autodetection of new fields.", "test_add_field_and_foo_together (migrations.test_autodetector.AutodetectorTests)", "#22030 - Adding a field with a default should work.", "Tests index/unique_together detection.", "Test change detection of new indexes.", "#22435 - Adding a ManyToManyField should not prompt for a default.", "test_add_model_order_with_respect_to (migrations.test_autodetector.AutodetectorTests)", "test_add_non_blank_textfield_and_charfield (migrations.test_autodetector.AutodetectorTests)", "Tests detection for adding db_table in model's options.", "Tests detection for changing db_table in model's options'.", "test_alter_db_table_no_changes (migrations.test_autodetector.AutodetectorTests)", "Tests detection for removing db_table in model's options.", "test_alter_db_table_with_model_change (migrations.test_autodetector.AutodetectorTests)", "test_alter_field_to_fk_dependency_other_app (migrations.test_autodetector.AutodetectorTests)", "test_alter_field_to_not_null_oneoff_default (migrations.test_autodetector.AutodetectorTests)", "test_alter_field_to_not_null_with_default (migrations.test_autodetector.AutodetectorTests)", "test_alter_field_to_not_null_without_default (migrations.test_autodetector.AutodetectorTests)", "test_alter_fk_before_model_deletion (migrations.test_autodetector.AutodetectorTests)", "test_alter_many_to_many (migrations.test_autodetector.AutodetectorTests)", "test_alter_model_managers (migrations.test_autodetector.AutodetectorTests)", "Changing a model's options should make a change.", "Changing a proxy model's options should also make a change.", "Tests auto-naming of migrations for graph matching.", "Bases of other models come first.", "test_circular_dependency_mixed_addcreate (migrations.test_autodetector.AutodetectorTests)", "test_circular_dependency_swappable (migrations.test_autodetector.AutodetectorTests)", "test_circular_dependency_swappable2 (migrations.test_autodetector.AutodetectorTests)", "test_circular_dependency_swappable_self (migrations.test_autodetector.AutodetectorTests)", "test_circular_fk_dependency (migrations.test_autodetector.AutodetectorTests)", "test_concrete_field_changed_to_many_to_many (migrations.test_autodetector.AutodetectorTests)", "test_create_model_and_unique_together (migrations.test_autodetector.AutodetectorTests)", "Test creation of new model with constraints already defined.", "Test creation of new model with indexes already defined.", "test_create_with_through_model (migrations.test_autodetector.AutodetectorTests)", "test_custom_deconstructible (migrations.test_autodetector.AutodetectorTests)", "Tests custom naming of migrations for graph matching.", "Field instances are handled correctly by nested deconstruction.", "test_deconstruct_type (migrations.test_autodetector.AutodetectorTests)", "Nested deconstruction descends into dict values.", "Nested deconstruction descends into lists.", "Nested deconstruction descends into tuples.", "test_default_related_name_option (migrations.test_autodetector.AutodetectorTests)", "test_different_regex_does_alter (migrations.test_autodetector.AutodetectorTests)", "test_empty_foo_together (migrations.test_autodetector.AutodetectorTests)", "test_first_dependency (migrations.test_autodetector.AutodetectorTests)", "Having a ForeignKey automatically adds a dependency.", "test_fk_dependency_other_app (migrations.test_autodetector.AutodetectorTests)", "test_foo_together_no_changes (migrations.test_autodetector.AutodetectorTests)", "test_foo_together_ordering (migrations.test_autodetector.AutodetectorTests)", "Tests unique_together and field removal detection & ordering", "test_foreign_key_removed_before_target_model (migrations.test_autodetector.AutodetectorTests)", "test_identical_regex_doesnt_alter (migrations.test_autodetector.AutodetectorTests)", "test_keep_db_table_with_model_change (migrations.test_autodetector.AutodetectorTests)", "test_last_dependency (migrations.test_autodetector.AutodetectorTests)", "test_m2m_w_through_multistep_remove (migrations.test_autodetector.AutodetectorTests)", "test_managed_to_unmanaged (migrations.test_autodetector.AutodetectorTests)", "test_many_to_many_changed_to_concrete_field (migrations.test_autodetector.AutodetectorTests)", "test_many_to_many_removed_before_through_model (migrations.test_autodetector.AutodetectorTests)", "test_many_to_many_removed_before_through_model_2 (migrations.test_autodetector.AutodetectorTests)", "test_mti_inheritance_model_removal (migrations.test_autodetector.AutodetectorTests)", "#23956 - Inheriting models doesn't move *_ptr fields into AddField operations.", "test_nested_deconstructible_objects (migrations.test_autodetector.AutodetectorTests)", "Tests autodetection of new models.", "test_non_circular_foreignkey_dependency_removal (migrations.test_autodetector.AutodetectorTests)", "Tests deletion of old models.", "Test change detection of reordering of fields in indexes.", "test_pk_fk_included (migrations.test_autodetector.AutodetectorTests)", "The autodetector correctly deals with proxy models.", "Bases of proxies come first.", "test_proxy_custom_pk (migrations.test_autodetector.AutodetectorTests)", "FK dependencies still work on proxy models.", "test_proxy_to_mti_with_fk_to_proxy (migrations.test_autodetector.AutodetectorTests)", "test_proxy_to_mti_with_fk_to_proxy_proxy (migrations.test_autodetector.AutodetectorTests)", "test_remove_alter_order_with_respect_to (migrations.test_autodetector.AutodetectorTests)", "Test change detection of removed constraints.", "Tests autodetection of removed fields.", "test_remove_field_and_foo_together (migrations.test_autodetector.AutodetectorTests)", "Test change detection of removed indexes.", "Tests autodetection of renamed fields.", "test_rename_field_and_foo_together (migrations.test_autodetector.AutodetectorTests)", "test_rename_field_foreign_key_to_field (migrations.test_autodetector.AutodetectorTests)", "test_rename_field_preserved_db_column (migrations.test_autodetector.AutodetectorTests)", "test_rename_foreign_object_fields (migrations.test_autodetector.AutodetectorTests)", "test_rename_m2m_through_model (migrations.test_autodetector.AutodetectorTests)", "Tests autodetection of renamed models.", "test_rename_model_reverse_relation_dependencies (migrations.test_autodetector.AutodetectorTests)", "test_rename_model_with_fks_in_different_position (migrations.test_autodetector.AutodetectorTests)", "test_rename_model_with_renamed_rel_field (migrations.test_autodetector.AutodetectorTests)", "test_rename_related_field_preserved_db_column (migrations.test_autodetector.AutodetectorTests)", "test_replace_string_with_foreignkey (migrations.test_autodetector.AutodetectorTests)", "test_same_app_circular_fk_dependency (migrations.test_autodetector.AutodetectorTests)", "test_same_app_circular_fk_dependency_with_unique_together_and_indexes (migrations.test_autodetector.AutodetectorTests)", "test_same_app_no_fk_dependency (migrations.test_autodetector.AutodetectorTests)", "Setting order_with_respect_to adds a field.", "test_supports_functools_partial (migrations.test_autodetector.AutodetectorTests)", "test_swappable (migrations.test_autodetector.AutodetectorTests)", "test_swappable_changed (migrations.test_autodetector.AutodetectorTests)", "test_swappable_circular_multi_mti (migrations.test_autodetector.AutodetectorTests)", "Swappable models get their CreateModel first.", "test_trim_apps (migrations.test_autodetector.AutodetectorTests)", "The autodetector correctly deals with managed models.", "test_unmanaged_custom_pk (migrations.test_autodetector.AutodetectorTests)", "test_unmanaged_delete (migrations.test_autodetector.AutodetectorTests)", "test_unmanaged_to_managed (migrations.test_autodetector.AutodetectorTests)"]
0668164b4ac93a5be79f5b87fae83c657124d9ab
django/django
django__django-12286
979f61abd322507aafced9627702362e541ec34e
diff --git a/django/core/checks/translation.py b/django/core/checks/translation.py --- a/django/core/checks/translation.py +++ b/django/core/checks/translation.py @@ -1,4 +1,5 @@ from django.conf import settings +from django.utils.translation import get_supported_language_variant from django.utils.translation.trans_real import language_code_re from . import Error, Tags, register @@ -55,7 +56,9 @@ def check_setting_languages_bidi(app_configs, **kwargs): @register(Tags.translation) def check_language_settings_consistent(app_configs, **kwargs): """Error if language settings are not consistent with each other.""" - available_tags = {i for i, _ in settings.LANGUAGES} | {'en-us'} - if settings.LANGUAGE_CODE not in available_tags: + try: + get_supported_language_variant(settings.LANGUAGE_CODE) + except LookupError: return [E004] - return [] + else: + return []
diff --git a/tests/check_framework/test_translation.py b/tests/check_framework/test_translation.py --- a/tests/check_framework/test_translation.py +++ b/tests/check_framework/test_translation.py @@ -3,7 +3,7 @@ check_language_settings_consistent, check_setting_language_code, check_setting_languages, check_setting_languages_bidi, ) -from django.test import SimpleTestCase +from django.test import SimpleTestCase, override_settings class TranslationCheckTests(SimpleTestCase): @@ -75,12 +75,36 @@ def test_invalid_languages_bidi(self): Error(msg % tag, id='translation.E003'), ]) + @override_settings(USE_I18N=True, LANGUAGES=[('en', 'English')]) def test_inconsistent_language_settings(self): msg = ( 'You have provided a value for the LANGUAGE_CODE setting that is ' 'not in the LANGUAGES setting.' ) - with self.settings(LANGUAGE_CODE='fr', LANGUAGES=[('en', 'English')]): - self.assertEqual(check_language_settings_consistent(None), [ - Error(msg, id='translation.E004'), - ]) + for tag in ['fr', 'fr-CA', 'fr-357']: + with self.subTest(tag), self.settings(LANGUAGE_CODE=tag): + self.assertEqual(check_language_settings_consistent(None), [ + Error(msg, id='translation.E004'), + ]) + + @override_settings( + USE_I18N=True, + LANGUAGES=[ + ('de', 'German'), + ('es', 'Spanish'), + ('fr', 'French'), + ('ca', 'Catalan'), + ], + ) + def test_valid_variant_consistent_language_settings(self): + tests = [ + # language + region. + 'fr-CA', + 'es-419', + 'de-at', + # language + region + variant. + 'ca-ES-valencia', + ] + for tag in tests: + with self.subTest(tag), self.settings(LANGUAGE_CODE=tag): + self.assertEqual(check_language_settings_consistent(None), [])
# Enhanced Problem Statement: Django translation.E004 Error with Valid Language Sublanguages ## Issue Description Django's system check framework incorrectly raises `translation.E004` error when a sublanguage (e.g., "de-at") is specified in `LANGUAGE_CODE` setting, even though its base language (e.g., "de") is available. This behavior contradicts Django's documentation which states: "If a base language is available but the sublanguage specified is not, Django uses the base language." The issue stems from an inconsistency between runtime language resolution (which properly handles fallbacks to base languages) and system validation checks (which strictly require an exact match in the `LANGUAGES` setting). This affects Django 3.0.2 and potentially other versions. ## Reproduction Steps 1. Configure a Django project with the following in settings.py: ```python LANGUAGE_CODE = "de-at" # Austrian German ``` 2. Run Django with this configuration (e.g., `python manage.py runserver`) 3. The system will raise the following error: ``` SystemCheckError: System check identified some issues: ERRORS: ?: (translation.E004) You have provided a value for the LANGUAGE_CODE setting that is not in the LANGUAGES setting. ``` 4. If you instead use `LANGUAGE_CODE = "es-ar"` (which is included in Django's default translations), Django works fine. Internally, what's happening is: - The system check in `django/core/checks/translation.py` is strictly checking if `LANGUAGE_CODE` is in `available_tags` - It's not using the `get_supported_language_variant()` function which would properly handle the fallback to "de" - At runtime, Django would correctly use "de" when "de-at" is requested, but the validation check fails before runtime ## Expected Behavior The system check should not raise `translation.E004` when a sublanguage is specified in `LANGUAGE_CODE` if its base language is available in the `LANGUAGES` setting. This would align with Django's documented behavior and runtime language resolution logic. ## Exploration Hints ### Files to Examine: - **django/core/checks/translation.py** - Contains the system check that raises the error. The `check_language_settings_consistent` function specifically checks if `LANGUAGE_CODE` is in `available_tags` without considering base language fallbacks. - **django/utils/translation/trans_real.py** - Contains the `get_supported_language_variant()` function that properly handles language fallbacks at runtime but isn't being used during system checks. - **django/utils/translation/__init__.py** - Core translation functionality that might provide context on how language codes are processed. ### Key Classes/Functions: - **check_language_settings_consistent()** in django/core/checks/translation.py - The function that performs the validation causing the issue. It needs to be updated to support base language fallbacks. - **get_supported_language_variant()** in django/utils/translation/trans_real.py - Contains the logic for language fallbacks that should be used or mimicked in the system check. - **language_code_re** - Regular expression used to validate language code formats. ### Areas of Interest: - The logic used to extract base languages from sublanguages (e.g., "de" from "de-at") - How `settings.LANGUAGES` is populated and checked against during system checks - How language resolution differs between validation time and runtime - The difference in behavior between built-in language codes (like "es-ar") and custom ones (like "de-at") ## Fix Hints ### High Confidence Locations: - **django/core/checks/translation.py** - The `check_language_settings_consistent` function needs modification to account for base language fallbacks when validating `LANGUAGE_CODE`. ### Implementation Hints: - Modify the check to use or mimic `get_supported_language_variant()` from trans_real.py - When checking if `settings.LANGUAGE_CODE` is valid, extract the base language when dealing with a hyphenated code - Only raise the E004 error if neither the full language code nor its base language is in `available_tags` - A simple implementation might check if the base language (everything before the first hyphen) is in `available_tags` ### Alternative Hypotheses: - The issue might involve conflicts between how language files are discovered and loaded versus how language codes are validated - There could be an intentional design decision to be more strict during system checks than during runtime (though this would contradict documentation) - The problem might relate to the initialization timing of language settings, where checks happen before certain language-related structures are fully populated
Thanks for this report. Regression in 4400d8296d268f5a8523cd02ddc33b12219b2535.
2020-01-07T13:56:28Z
3.1
["test_valid_variant_consistent_language_settings (check_framework.test_translation.TranslationCheckTests)"]
["test_inconsistent_language_settings (check_framework.test_translation.TranslationCheckTests)", "test_invalid_language_code (check_framework.test_translation.TranslationCheckTests)", "test_invalid_languages (check_framework.test_translation.TranslationCheckTests)", "test_invalid_languages_bidi (check_framework.test_translation.TranslationCheckTests)", "test_valid_language_code (check_framework.test_translation.TranslationCheckTests)", "test_valid_languages (check_framework.test_translation.TranslationCheckTests)", "test_valid_languages_bidi (check_framework.test_translation.TranslationCheckTests)"]
0668164b4ac93a5be79f5b87fae83c657124d9ab
django/django
django__django-12747
c86201b6ed4f8256b0a0520c08aa674f623d4127
diff --git a/django/db/models/deletion.py b/django/db/models/deletion.py --- a/django/db/models/deletion.py +++ b/django/db/models/deletion.py @@ -408,7 +408,8 @@ def delete(self): # fast deletes for qs in self.fast_deletes: count = qs._raw_delete(using=self.using) - deleted_counter[qs.model._meta.label] += count + if count: + deleted_counter[qs.model._meta.label] += count # update fields for model, instances_for_fieldvalues in self.field_updates.items(): @@ -426,7 +427,8 @@ def delete(self): query = sql.DeleteQuery(model) pk_list = [obj.pk for obj in instances] count = query.delete_batch(pk_list, self.using) - deleted_counter[model._meta.label] += count + if count: + deleted_counter[model._meta.label] += count if not model._meta.auto_created: for obj in instances:
diff --git a/tests/delete/tests.py b/tests/delete/tests.py --- a/tests/delete/tests.py +++ b/tests/delete/tests.py @@ -522,11 +522,10 @@ def test_queryset_delete_returns_num_rows(self): existed_objs = { R._meta.label: R.objects.count(), HiddenUser._meta.label: HiddenUser.objects.count(), - A._meta.label: A.objects.count(), - MR._meta.label: MR.objects.count(), HiddenUserProfile._meta.label: HiddenUserProfile.objects.count(), } deleted, deleted_objs = R.objects.all().delete() + self.assertCountEqual(deleted_objs.keys(), existed_objs.keys()) for k, v in existed_objs.items(): self.assertEqual(deleted_objs[k], v) @@ -550,13 +549,13 @@ def test_model_delete_returns_num_rows(self): existed_objs = { R._meta.label: R.objects.count(), HiddenUser._meta.label: HiddenUser.objects.count(), - A._meta.label: A.objects.count(), MR._meta.label: MR.objects.count(), HiddenUserProfile._meta.label: HiddenUserProfile.objects.count(), M.m2m.through._meta.label: M.m2m.through.objects.count(), } deleted, deleted_objs = r.delete() self.assertEqual(deleted, sum(existed_objs.values())) + self.assertCountEqual(deleted_objs.keys(), existed_objs.keys()) for k, v in existed_objs.items(): self.assertEqual(deleted_objs[k], v) @@ -694,7 +693,7 @@ def test_fast_delete_empty_no_update_can_self_select(self): with self.assertNumQueries(1): self.assertEqual( User.objects.filter(avatar__desc='missing').delete(), - (0, {'delete.User': 0}) + (0, {}), ) def test_fast_delete_combined_relationships(self):
# QuerySet.Delete: Inconsistent Results When Zero Objects Deleted ## Issue Description The `QuerySet.delete()` method returns inconsistent results when no objects are deleted. This method returns a tuple `(total_count, model_counts)`, where `total_count` is the total number of deleted objects (including cascaded deletions) and `model_counts` is a dictionary mapping model labels to deletion counts. The inconsistency occurs when zero objects are deleted: - For models with foreign keys: `(0, {})` - For "simple" models without foreign keys: `(0, {'my_app.ModelName': 0})` This inconsistent behavior complicates error handling and creates unpredictable API responses for consumers. ## Reproduction Steps ```python # For a model with foreign keys related_objects = RelatedModel.objects.filter(id=-999) # Non-existent ID result = related_objects.delete() print(result) # Output: (0, {}) # For a "simple" model without foreign keys simple_objects = SimpleModel.objects.filter(id=-999) # Non-existent ID result = simple_objects.delete() print(result) # Output: (0, {'app_name.SimpleModel': 0}) ``` Internally, the issue arises from how the Django deletion collector handles different model types. For models with foreign keys, the collector uses cascading deletion machinery which may not add the model to the tracking dictionary when no objects exist. For simple models, the model is tracked with a zero count even when no objects are found. ## Expected Behavior The return value format should be consistent regardless of model type. Either: 1. Both cases should return `(0, {})` when no objects are deleted, OR 2. Both cases should return `(0, {'app_name.ModelName': 0})`, including the model in the dictionary with a zero count The second approach is likely better for API consumers as it always includes the model in the result, making the return format more predictable. ## Exploration Hints ### Files to Examine: - **django/db/models/query.py** - Contains the `QuerySet` class with the `delete()` method that returns the inconsistent tuple. This method delegates to a collector that gathers and performs deletions. - **django/db/models/deletion.py** - Contains the `Collector` class responsible for tracking objects by model type and performing deletions. The inconsistency likely originates in how this class builds the result dictionary. ### Key Classes/Functions: - **QuerySet.delete()** - The public method that exhibits the inconsistent behavior. Calls `Collector.delete()` and returns its result. - **QuerySet._raw_delete()** - Called by `delete()`, this may handle some model-specific logic. - **Collector.delete()** - Orchestrates deletion and builds the result tuple. The inconsistency likely originates here in how it tracks deletions by model type. - **Collector.collect()** - Gathers objects for deletion, including cascaded deletes for related objects. ### Areas of Interest: - How the `data_objs` dictionary in the `Collector` class is populated during collection and deletion - The conditions under which model labels are added to or excluded from the result dictionary - Different code paths for models with relationships versus simple models - How deletion counts are tracked and reported in the final result tuple ## Fix Hints ### High Confidence Locations: - `Collector.delete()` in django/db/models/deletion.py is the most likely fix location. This method constructs the result tuple and dictionary that shows the inconsistent behavior. ### Implementation Hints: 1. The fix likely involves normalizing how models are tracked in the deletion process: - Always add the model to the result dictionary, even if the count is zero, OR - Never add models with zero deletions to the dictionary 2. A simple approach might be to ensure the collector consistently initializes the count for the primary model being deleted, even when no objects are found. 3. The fix should be careful to preserve the existing behavior for cases where objects are actually deleted. ### Alternative Hypotheses: 1. The issue might originate in how `QuerySet.delete()` calls `Collector.delete()` rather than in the `Collector` itself. 2. The inconsistency could be in the collection phase rather than the deletion phase - objects for simple models might always be "collected" (even if none exist) while related models are only collected if they actually exist. 3. There could be optimization logic that skips certain steps for models with foreign keys when no objects are found, resulting in different dictionary construction. 4. The behavior might be related to how SQL queries are constructed and their results processed differently for different model types.
I guess we could adapt the code not to include any key if the count is zero in the second case.
2020-04-18T16:41:40Z
3.1
["test_fast_delete_empty_no_update_can_self_select (delete.tests.FastDeleteTests)", "test_model_delete_returns_num_rows (delete.tests.DeletionTests)", "test_queryset_delete_returns_num_rows (delete.tests.DeletionTests)"]
["test_fast_delete_combined_relationships (delete.tests.FastDeleteTests)", "test_fast_delete_fk (delete.tests.FastDeleteTests)", "test_fast_delete_inheritance (delete.tests.FastDeleteTests)", "test_fast_delete_instance_set_pk_none (delete.tests.FastDeleteTests)", "test_fast_delete_joined_qs (delete.tests.FastDeleteTests)", "test_fast_delete_large_batch (delete.tests.FastDeleteTests)", "test_fast_delete_m2m (delete.tests.FastDeleteTests)", "test_fast_delete_qs (delete.tests.FastDeleteTests)", "test_fast_delete_revm2m (delete.tests.FastDeleteTests)", "test_auto (delete.tests.OnDeleteTests)", "test_auto_nullable (delete.tests.OnDeleteTests)", "test_cascade (delete.tests.OnDeleteTests)", "test_cascade_from_child (delete.tests.OnDeleteTests)", "test_cascade_from_parent (delete.tests.OnDeleteTests)", "test_cascade_nullable (delete.tests.OnDeleteTests)", "test_do_nothing (delete.tests.OnDeleteTests)", "test_do_nothing_qscount (delete.tests.OnDeleteTests)", "test_inheritance_cascade_down (delete.tests.OnDeleteTests)", "test_inheritance_cascade_up (delete.tests.OnDeleteTests)", "test_non_callable (delete.tests.OnDeleteTests)", "test_o2o_setnull (delete.tests.OnDeleteTests)", "test_protect (delete.tests.OnDeleteTests)", "test_protect_multiple (delete.tests.OnDeleteTests)", "test_protect_path (delete.tests.OnDeleteTests)", "test_restrict (delete.tests.OnDeleteTests)", "test_restrict_gfk_no_fast_delete (delete.tests.OnDeleteTests)", "test_restrict_multiple (delete.tests.OnDeleteTests)", "test_restrict_path_cascade_direct (delete.tests.OnDeleteTests)", "test_restrict_path_cascade_indirect (delete.tests.OnDeleteTests)", "test_restrict_path_cascade_indirect_diamond (delete.tests.OnDeleteTests)", "test_setdefault (delete.tests.OnDeleteTests)", "test_setdefault_none (delete.tests.OnDeleteTests)", "test_setnull (delete.tests.OnDeleteTests)", "test_setnull_from_child (delete.tests.OnDeleteTests)", "test_setnull_from_parent (delete.tests.OnDeleteTests)", "test_setvalue (delete.tests.OnDeleteTests)", "test_bulk (delete.tests.DeletionTests)", "test_can_defer_constraint_checks (delete.tests.DeletionTests)", "test_delete_with_keeping_parents (delete.tests.DeletionTests)", "test_delete_with_keeping_parents_relationships (delete.tests.DeletionTests)", "test_deletion_order (delete.tests.DeletionTests)", "test_hidden_related (delete.tests.DeletionTests)", "test_instance_update (delete.tests.DeletionTests)", "test_large_delete (delete.tests.DeletionTests)", "test_large_delete_related (delete.tests.DeletionTests)", "test_m2m (delete.tests.DeletionTests)", "test_only_referenced_fields_selected (delete.tests.DeletionTests)", "test_proxied_model_duplicate_queries (delete.tests.DeletionTests)", "test_relational_post_delete_signals_happen_before_parent_object (delete.tests.DeletionTests)"]
0668164b4ac93a5be79f5b87fae83c657124d9ab
django/django
django__django-13768
965d2d95c630939b53eb60d9c169f5dfc77ee0c6
diff --git a/django/dispatch/dispatcher.py b/django/dispatch/dispatcher.py --- a/django/dispatch/dispatcher.py +++ b/django/dispatch/dispatcher.py @@ -1,3 +1,4 @@ +import logging import threading import warnings import weakref @@ -5,6 +6,8 @@ from django.utils.deprecation import RemovedInDjango40Warning from django.utils.inspect import func_accepts_kwargs +logger = logging.getLogger('django.dispatch') + def _make_id(target): if hasattr(target, '__func__'): @@ -208,6 +211,12 @@ def send_robust(self, sender, **named): try: response = receiver(signal=self, sender=sender, **named) except Exception as err: + logger.error( + 'Error calling %s in Signal.send_robust() (%s)', + receiver.__qualname__, + err, + exc_info=err, + ) responses.append((receiver, err)) else: responses.append((receiver, response))
diff --git a/tests/dispatch/tests.py b/tests/dispatch/tests.py --- a/tests/dispatch/tests.py +++ b/tests/dispatch/tests.py @@ -165,13 +165,28 @@ def test_send_robust_fail(self): def fails(val, **kwargs): raise ValueError('this') a_signal.connect(fails) - result = a_signal.send_robust(sender=self, val="test") - err = result[0][1] - self.assertIsInstance(err, ValueError) - self.assertEqual(err.args, ('this',)) - self.assertTrue(hasattr(err, '__traceback__')) - self.assertIsInstance(err.__traceback__, TracebackType) - a_signal.disconnect(fails) + try: + with self.assertLogs('django.dispatch', 'ERROR') as cm: + result = a_signal.send_robust(sender=self, val='test') + err = result[0][1] + self.assertIsInstance(err, ValueError) + self.assertEqual(err.args, ('this',)) + self.assertIs(hasattr(err, '__traceback__'), True) + self.assertIsInstance(err.__traceback__, TracebackType) + + log_record = cm.records[0] + self.assertEqual( + log_record.getMessage(), + 'Error calling ' + 'DispatcherTests.test_send_robust_fail.<locals>.fails in ' + 'Signal.send_robust() (this)', + ) + self.assertIsNotNone(log_record.exc_info) + _, exc_value, _ = log_record.exc_info + self.assertIsInstance(exc_value, ValueError) + self.assertEqual(str(exc_value), 'this') + finally: + a_signal.disconnect(fails) self.assertTestIsClean(a_signal) def test_disconnection(self):
# Enhanced Problem Statement: Signal Exception Logging ## Issue Description Django's `Signal.send_robust()` method silently catches exceptions raised in signal receivers without logging them, contrary to Django's usual practice of logging exceptions in similar situations (such as missing template variables). This creates a debugging blind spot where errors in signal handlers go unnoticed unless the caller explicitly checks the return values. This lack of visibility is particularly problematic for error monitoring tools like Sentry that rely on logs to capture and report issues in production environments. The issue requires adding logging capabilities to the exception handling in `send_robust()` while maintaining its current behavior of continuing execution after receiver exceptions. ## Reproduction Steps 1. Create a Django signal: ```python from django.dispatch import Signal my_signal = Signal() ``` 2. Register a receiver that raises an exception: ```python @my_signal.connect def failing_receiver(sender, **kwargs): raise ValueError("Test exception in signal receiver") ``` 3. Call `send_robust()` on the signal: ```python results = my_signal.send_robust(sender=None) ``` 4. Observe that the exception is caught and returned in the results, but nothing is logged: ```python for receiver, response in results: if isinstance(response, Exception): print(f"Exception occurred in {receiver}: {response}") ``` Internally, `send_robust()` catches exceptions in a `try/except Exception` block but doesn't use Django's logging framework to record these exceptions, making them invisible to error tracking systems unless explicitly processed by the caller. ## Expected Behavior When an exception occurs in a signal receiver during `send_robust()` execution: 1. The exception should be logged using `logger.exception()` to capture the full traceback 2. The current behavior of catching the exception and continuing execution should be preserved 3. The return value format (a list of (receiver, response) tuples) should remain unchanged 4. The exception should still be included in the return value as it is now This would align with Django's approach in other areas where exceptions are logged for visibility while allowing execution to continue. ## Exploration Hints ### Files to Examine: - **django/dispatch/dispatcher.py** - Contains the core implementation of Django's signal dispatch system, particularly the `Signal` class with its `send_robust()` method. This is the primary file where changes will be needed. ### Key Classes/Functions: - **Signal.send_robust()** - The method that catches exceptions from signal receivers but doesn't log them. This method returns a list of (receiver, response) tuples where response can be either the return value or an exception instance. The method's exception handling block needs modification to add logging. ### Areas of Interest: - The exception handling in `send_robust()` likely has a structure similar to: ```python try: response = receiver(signal=self, sender=sender, **named) except Exception as err: response = err ``` - The logging implementation should preserve the exception context to ensure stacktraces are properly captured - Django's logging conventions should be followed (likely using `logging.getLogger(__name__)`) ## Fix Hints ### High Confidence Locations: - The `except Exception as err:` block in the `send_robust()` method is where logging should be added while keeping the existing behavior of assigning the exception to `response`. ### Implementation Hints: - Import the logging module at the top of the file: `import logging` - Create a logger instance: `logger = logging.getLogger(__name__)` - Add a logging statement in the exception block: ```python except Exception as err: logger.exception("Exception raised by %s when handling '%s' signal", receiver_object, self.name) response = err ``` - Ensure the log message includes context about which receiver failed and for what signal - The logging level should be ERROR since this represents an unhandled exception in user code ### Alternative Hypotheses: - There may be performance concerns if signals with many receivers frequently encounter exceptions, resulting in excessive logging. If this becomes an issue, a configurable logging threshold or rate limiting could be considered. - Some users might rely on the current silent behavior. Adding logging changes the side effects of the method, though not its return values. Consider whether this would be a backward-incompatible change in practice. - There might be value in adding a parameter to control whether exceptions are logged (e.g., `log_exceptions=True`), allowing users to maintain the current behavior if desired.
I would like to work on this issue. PS. i am new to this django. so any advice would be appreciated
2020-12-12T07:34:48Z
3.2
["test_send_robust_fail (dispatch.tests.DispatcherTests)"]
["test_receiver_signal_list (dispatch.tests.ReceiverTestCase)", "test_receiver_single_signal (dispatch.tests.ReceiverTestCase)", "test_cached_garbaged_collected (dispatch.tests.DispatcherTests)", "test_cannot_connect_no_kwargs (dispatch.tests.DispatcherTests)", "test_cannot_connect_non_callable (dispatch.tests.DispatcherTests)", "test_disconnection (dispatch.tests.DispatcherTests)", "test_garbage_collected (dispatch.tests.DispatcherTests)", "test_has_listeners (dispatch.tests.DispatcherTests)", "test_multiple_registration (dispatch.tests.DispatcherTests)", "test_send (dispatch.tests.DispatcherTests)", "test_send_connected_no_sender (dispatch.tests.DispatcherTests)", "test_send_different_no_sender (dispatch.tests.DispatcherTests)", "test_send_no_receivers (dispatch.tests.DispatcherTests)", "test_send_robust_ignored_sender (dispatch.tests.DispatcherTests)", "test_send_robust_no_receivers (dispatch.tests.DispatcherTests)", "test_send_robust_success (dispatch.tests.DispatcherTests)", "test_uid_registration (dispatch.tests.DispatcherTests)", "test_values_returned_by_disconnection (dispatch.tests.DispatcherTests)"]
65dfb06a1ab56c238cc80f5e1c31f61210c4577d
django/django
django__django-12708
447980e72ac01da1594dd3373a03ba40b7ee6f80
diff --git a/django/db/backends/base/schema.py b/django/db/backends/base/schema.py --- a/django/db/backends/base/schema.py +++ b/django/db/backends/base/schema.py @@ -393,7 +393,12 @@ def alter_index_together(self, model, old_index_together, new_index_together): news = {tuple(fields) for fields in new_index_together} # Deleted indexes for fields in olds.difference(news): - self._delete_composed_index(model, fields, {'index': True}, self.sql_delete_index) + self._delete_composed_index( + model, + fields, + {'index': True, 'unique': False}, + self.sql_delete_index, + ) # Created indexes for field_names in news.difference(olds): fields = [model._meta.get_field(field) for field in field_names]
diff --git a/tests/migrations/test_base.py b/tests/migrations/test_base.py --- a/tests/migrations/test_base.py +++ b/tests/migrations/test_base.py @@ -62,7 +62,11 @@ def assertIndexExists(self, table, columns, value=True, using='default', index_t any( c["index"] for c in connections[using].introspection.get_constraints(cursor, table).values() - if c['columns'] == list(columns) and (index_type is None or c['type'] == index_type) + if ( + c['columns'] == list(columns) and + (index_type is None or c['type'] == index_type) and + not c['unique'] + ) ), ) @@ -80,6 +84,14 @@ def assertConstraintExists(self, table, name, value=True, using='default'): def assertConstraintNotExists(self, table, name): return self.assertConstraintExists(table, name, False) + def assertUniqueConstraintExists(self, table, columns, value=True, using='default'): + with connections[using].cursor() as cursor: + constraints = connections[using].introspection.get_constraints(cursor, table).values() + self.assertEqual( + value, + any(c['unique'] for c in constraints if c['columns'] == list(columns)), + ) + def assertFKExists(self, table, columns, to, value=True, using='default'): with connections[using].cursor() as cursor: self.assertEqual( diff --git a/tests/migrations/test_operations.py b/tests/migrations/test_operations.py --- a/tests/migrations/test_operations.py +++ b/tests/migrations/test_operations.py @@ -1759,6 +1759,29 @@ def test_alter_index_together_remove(self): operation = migrations.AlterIndexTogether("Pony", None) self.assertEqual(operation.describe(), "Alter index_together for Pony (0 constraint(s))") + @skipUnlessDBFeature('allows_multiple_constraints_on_same_fields') + def test_alter_index_together_remove_with_unique_together(self): + app_label = 'test_alintoremove_wunto' + table_name = '%s_pony' % app_label + project_state = self.set_up_test_model(app_label, unique_together=True) + self.assertUniqueConstraintExists(table_name, ['pink', 'weight']) + # Add index together. + new_state = project_state.clone() + operation = migrations.AlterIndexTogether('Pony', [('pink', 'weight')]) + operation.state_forwards(app_label, new_state) + with connection.schema_editor() as editor: + operation.database_forwards(app_label, editor, project_state, new_state) + self.assertIndexExists(table_name, ['pink', 'weight']) + # Remove index together. + project_state = new_state + new_state = project_state.clone() + operation = migrations.AlterIndexTogether('Pony', set()) + operation.state_forwards(app_label, new_state) + with connection.schema_editor() as editor: + operation.database_forwards(app_label, editor, project_state, new_state) + self.assertIndexNotExists(table_name, ['pink', 'weight']) + self.assertUniqueConstraintExists(table_name, ['pink', 'weight']) + @skipUnlessDBFeature('supports_table_check_constraints') def test_add_constraint(self): project_state = self.set_up_test_model("test_addconstraint")
# Migration Crashes When Deleting index_together with Overlapping unique_together ## Issue Description In Django 1.11.10, there's a critical issue when attempting to delete an `index_together` constraint that shares the same fields with a `unique_together` constraint. The migration system fails to distinguish between these two types of constraints when they cover the same database columns. The issue manifests as a `ValueError` with the message "Found wrong number (2) of constraints" in the `_delete_composed_index()` method of Django's schema editor. This occurs because the schema editor identifies both the unique constraint and the index constraint when trying to delete just the index, and it doesn't have logic to determine which one to remove. This problem particularly affects users who are trying to refactor their code to use Django 1.11's newer `Options.indexes` feature instead of the legacy `index_together` approach. In such cases, even though users are just changing the declaration method (not actually removing the index functionality), Django attempts to delete and recreate the index during migration, causing the error. ## Reproduction Steps 1. Create models with 2 fields that are included in both `unique_together` and `index_together`: ```python class MyModel(models.Model): field1 = models.CharField(max_length=100) field2 = models.CharField(max_length=100) class Meta: unique_together = (('field1', 'field2'),) index_together = (('field1', 'field2'),) ``` 2. Create and apply initial migration to set up the model with both constraints 3. Update the model to remove the `index_together` constraint (but keep the `unique_together`): ```python class MyModel(models.Model): field1 = models.CharField(max_length=100) field2 = models.CharField(max_length=100) class Meta: unique_together = (('field1', 'field2'),) # index_together removed ``` 4. Attempt to create and apply migration 5. The migration will fail with a `ValueError: Found wrong number (2) of constraints` error at `django/db/backends/base/schema.py`, line 378, in the `_delete_composed_index()` method. What happens internally: - The migration system correctly detects the removal of the `index_together` constraint - It attempts to identify and delete the corresponding database index - When querying the database for constraints on these fields, it finds two: one from `unique_together` (which creates a unique index) and one from `index_together` - The `_delete_composed_index()` method expects to find exactly one constraint, causing it to raise the error ## Expected Behavior Django should be able to: 1. Properly identify which constraint to delete when `index_together` and `unique_together` overlap 2. Successfully delete only the index constraint while preserving the unique constraint 3. Allow smooth transition from `index_together` to `Options.indexes` without requiring deletion and recreation of indexes ## Exploration Hints ### Files to Examine: - **django/db/backends/base/schema.py** - Contains the `_delete_composed_index()` method where the error occurs (line 378). This method is failing to distinguish between unique constraints and regular indexes when they cover the same fields. - **django/db/models/options.py** - Contains the `Options` class that handles both `unique_together` and `index_together` attributes. The issue occurs at the intersection of these two features, and this file defines how they're processed. - **django/db/migrations/operations/models.py** - Contains the `AlterUniqueTogether` and `AlterIndexTogether` operations, which handle these model changes during migrations. - **django/db/backends/base/introspection.py** - Provides the `get_constraints()` method that's used to identify database constraints, which is crucial to understanding how Django identifies what to delete. ### Key Classes/Functions: - **SchemaEditor._delete_composed_index()** - Responsible for deleting composite indexes; fails when it finds both a unique constraint and an index constraint on the same fields. - **Options.normalize_together()** - Normalizes both `unique_together` and `index_together` declarations, possibly not providing enough differentiation for deletion operations. - **AlterIndexTogether.database_forwards()/database_backwards()** - Methods that translate model changes to schema operations; may need to better handle overlaps with `unique_together`. - **BaseDatabaseIntrospection.get_constraints()** - The abstract method implemented by database backends to identify existing constraints; may not provide sufficient information to distinguish between constraint types. ### Areas of Interest: - Constraint naming patterns and how they might lead to ambiguity - How Django differentiates between unique constraints and regular indexes - The process of transitioning from `index_together` to `Options.indexes` and why it involves index deletion - Database-specific behaviors regarding unique constraints and their implicit indexes ## Fix Hints ### High Confidence Locations: - **SchemaEditor._delete_composed_index()** in django/db/backends/base/schema.py - This is the most likely fix location as it's where the error is raised. The method needs to be updated to handle cases where multiple constraints (both unique and index) exist on the same fields. ### Implementation Hints: - Modify `_delete_composed_index()` to filter constraints by type (unique vs. index) when identifying which one to delete - Add a parameter to the function to specify whether to target only indexes or only unique constraints - Consider enhancing the constraint identification logic to use additional metadata beyond just field names - For the refactoring use case (moving from `index_together` to `Options.indexes`), consider adding detection logic that avoids unnecessary index deletion and recreation ### Alternative Hypotheses: - The issue might be database-specific, with different database backends handling composite indexes differently - The constraint naming convention might be inconsistent, making it impossible to reliably distinguish between constraint types - There could be a deeper architectural issue in how Django tracks the "purpose" or "origin" of database constraints throughout their lifecycle - The migration framework may need broader changes to correctly track which constraints were created by which model declaration methods
Reproduced on master at 623139b5d1bd006eac78b375bcaf5948e695c3c6. I haven't looked under the hood on this yet, but could it be related to the ordering of the operations generated for the mgiration? on first inspection it feels like this and #28862 could be caused by the same/similar underlying problem in how FieldRelatedOptionOperation subclasses ordering is handled in the migration autodetector's migration optimizer.
2020-04-12T22:20:59Z
3.1
["test_alter_index_together_remove_with_unique_together (migrations.test_operations.OperationTests)"]
["test_references_model_mixin (migrations.test_operations.TestCreateModel)", "test_reference_field_by_through_fields (migrations.test_operations.FieldOperationTests)", "test_references_field_by_from_fields (migrations.test_operations.FieldOperationTests)", "test_references_field_by_name (migrations.test_operations.FieldOperationTests)", "test_references_field_by_remote_field_model (migrations.test_operations.FieldOperationTests)", "test_references_field_by_through (migrations.test_operations.FieldOperationTests)", "test_references_field_by_to_fields (migrations.test_operations.FieldOperationTests)", "test_references_model (migrations.test_operations.FieldOperationTests)", "test_add_field_ignore_swapped (migrations.test_operations.SwappableOperationTests)", "test_create_ignore_swapped (migrations.test_operations.SwappableOperationTests)", "test_delete_ignore_swapped (migrations.test_operations.SwappableOperationTests)", "test_indexes_ignore_swapped (migrations.test_operations.SwappableOperationTests)", "test_add_binaryfield (migrations.test_operations.OperationTests)", "test_add_charfield (migrations.test_operations.OperationTests)", "test_add_constraint (migrations.test_operations.OperationTests)", "test_add_constraint_combinable (migrations.test_operations.OperationTests)", "test_add_constraint_percent_escaping (migrations.test_operations.OperationTests)", "test_add_field (migrations.test_operations.OperationTests)", "test_add_field_m2m (migrations.test_operations.OperationTests)", "test_add_field_preserve_default (migrations.test_operations.OperationTests)", "test_add_index (migrations.test_operations.OperationTests)", "test_add_index_state_forwards (migrations.test_operations.OperationTests)", "test_add_or_constraint (migrations.test_operations.OperationTests)", "test_add_partial_unique_constraint (migrations.test_operations.OperationTests)", "test_add_textfield (migrations.test_operations.OperationTests)", "test_alter_field (migrations.test_operations.OperationTests)", "test_alter_field_m2m (migrations.test_operations.OperationTests)", "test_alter_field_pk (migrations.test_operations.OperationTests)", "test_alter_field_pk_fk (migrations.test_operations.OperationTests)", "test_alter_field_reloads_state_on_fk_target_changes (migrations.test_operations.OperationTests)", "test_alter_field_reloads_state_on_fk_with_to_field_related_name_target_type_change (migrations.test_operations.OperationTests)", "test_alter_field_reloads_state_on_fk_with_to_field_target_changes (migrations.test_operations.OperationTests)", "test_alter_field_reloads_state_on_fk_with_to_field_target_type_change (migrations.test_operations.OperationTests)", "test_alter_field_with_index (migrations.test_operations.OperationTests)", "test_alter_fk (migrations.test_operations.OperationTests)", "test_alter_fk_non_fk (migrations.test_operations.OperationTests)", "test_alter_index_together (migrations.test_operations.OperationTests)", "test_alter_index_together_remove (migrations.test_operations.OperationTests)", "test_alter_model_managers (migrations.test_operations.OperationTests)", "test_alter_model_managers_emptying (migrations.test_operations.OperationTests)", "test_alter_model_options (migrations.test_operations.OperationTests)", "test_alter_model_options_emptying (migrations.test_operations.OperationTests)", "test_alter_model_table (migrations.test_operations.OperationTests)", "test_alter_model_table_m2m (migrations.test_operations.OperationTests)", "test_alter_model_table_none (migrations.test_operations.OperationTests)", "test_alter_model_table_noop (migrations.test_operations.OperationTests)", "test_alter_order_with_respect_to (migrations.test_operations.OperationTests)", "test_alter_unique_together (migrations.test_operations.OperationTests)", "test_alter_unique_together_remove (migrations.test_operations.OperationTests)", "A field may be migrated from AutoField to BigAutoField.", "test_column_name_quoting (migrations.test_operations.OperationTests)", "test_create_model (migrations.test_operations.OperationTests)", "test_create_model_inheritance (migrations.test_operations.OperationTests)", "test_create_model_m2m (migrations.test_operations.OperationTests)", "test_create_model_managers (migrations.test_operations.OperationTests)", "test_create_model_with_constraint (migrations.test_operations.OperationTests)", "test_create_model_with_duplicate_base (migrations.test_operations.OperationTests)", "test_create_model_with_duplicate_field_name (migrations.test_operations.OperationTests)", "test_create_model_with_duplicate_manager_name (migrations.test_operations.OperationTests)", "test_create_model_with_partial_unique_constraint (migrations.test_operations.OperationTests)", "test_create_model_with_unique_after (migrations.test_operations.OperationTests)", "test_create_proxy_model (migrations.test_operations.OperationTests)", "test_create_unmanaged_model (migrations.test_operations.OperationTests)", "test_delete_model (migrations.test_operations.OperationTests)", "test_delete_mti_model (migrations.test_operations.OperationTests)", "test_delete_proxy_model (migrations.test_operations.OperationTests)", "test_model_with_bigautofield (migrations.test_operations.OperationTests)", "test_remove_constraint (migrations.test_operations.OperationTests)", "test_remove_field (migrations.test_operations.OperationTests)", "test_remove_field_m2m (migrations.test_operations.OperationTests)", "test_remove_field_m2m_with_through (migrations.test_operations.OperationTests)", "test_remove_fk (migrations.test_operations.OperationTests)", "test_remove_index (migrations.test_operations.OperationTests)", "test_remove_index_state_forwards (migrations.test_operations.OperationTests)", "test_remove_partial_unique_constraint (migrations.test_operations.OperationTests)", "test_rename_field (migrations.test_operations.OperationTests)", "test_rename_field_reloads_state_on_fk_target_changes (migrations.test_operations.OperationTests)", "RenameModel renames a many-to-many column after a RenameField.", "test_rename_m2m_target_model (migrations.test_operations.OperationTests)", "test_rename_m2m_through_model (migrations.test_operations.OperationTests)", "test_rename_missing_field (migrations.test_operations.OperationTests)", "test_rename_model (migrations.test_operations.OperationTests)", "test_rename_model_state_forwards (migrations.test_operations.OperationTests)", "test_rename_model_with_m2m (migrations.test_operations.OperationTests)", "test_rename_model_with_self_referential_fk (migrations.test_operations.OperationTests)", "test_rename_model_with_self_referential_m2m (migrations.test_operations.OperationTests)", "test_rename_model_with_superclass_fk (migrations.test_operations.OperationTests)", "test_rename_referenced_field_state_forward (migrations.test_operations.OperationTests)", "test_repoint_field_m2m (migrations.test_operations.OperationTests)", "test_run_python (migrations.test_operations.OperationTests)", "test_run_python_atomic (migrations.test_operations.OperationTests)", "test_run_python_noop (migrations.test_operations.OperationTests)", "test_run_python_related_assignment (migrations.test_operations.OperationTests)", "test_run_sql (migrations.test_operations.OperationTests)", "test_run_sql_noop (migrations.test_operations.OperationTests)", "test_run_sql_params (migrations.test_operations.OperationTests)", "test_run_sql_params_invalid (migrations.test_operations.OperationTests)", "test_separate_database_and_state (migrations.test_operations.OperationTests)", "test_separate_database_and_state2 (migrations.test_operations.OperationTests)", "A field may be migrated from SmallAutoField to AutoField.", "A field may be migrated from SmallAutoField to BigAutoField."]
0668164b4ac93a5be79f5b87fae83c657124d9ab
django/django
django__django-13321
35b03788b0607c1f8d2b64e4fa9e1669b0907ea4
diff --git a/django/contrib/sessions/backends/base.py b/django/contrib/sessions/backends/base.py --- a/django/contrib/sessions/backends/base.py +++ b/django/contrib/sessions/backends/base.py @@ -121,6 +121,15 @@ def decode(self, session_data): return signing.loads(session_data, salt=self.key_salt, serializer=self.serializer) # RemovedInDjango40Warning: when the deprecation ends, handle here # exceptions similar to what _legacy_decode() does now. + except signing.BadSignature: + try: + # Return an empty session if data is not in the pre-Django 3.1 + # format. + return self._legacy_decode(session_data) + except Exception: + logger = logging.getLogger('django.security.SuspiciousSession') + logger.warning('Session data corrupted') + return {} except Exception: return self._legacy_decode(session_data)
diff --git a/tests/sessions_tests/tests.py b/tests/sessions_tests/tests.py --- a/tests/sessions_tests/tests.py +++ b/tests/sessions_tests/tests.py @@ -333,11 +333,16 @@ def test_default_hashing_algorith_legacy_decode(self): self.assertEqual(self.session._legacy_decode(encoded), data) def test_decode_failure_logged_to_security(self): - bad_encode = base64.b64encode(b'flaskdj:alkdjf').decode('ascii') - with self.assertLogs('django.security.SuspiciousSession', 'WARNING') as cm: - self.assertEqual({}, self.session.decode(bad_encode)) - # The failed decode is logged. - self.assertIn('corrupted', cm.output[0]) + tests = [ + base64.b64encode(b'flaskdj:alkdjf').decode('ascii'), + 'bad:encoded:value', + ] + for encoded in tests: + with self.subTest(encoded=encoded): + with self.assertLogs('django.security.SuspiciousSession', 'WARNING') as cm: + self.assertEqual(self.session.decode(encoded), {}) + # The failed decode is logged. + self.assertIn('Session data corrupted', cm.output[0]) def test_actual_expiry(self): # this doesn't work with JSONSerializer (serializing timedelta)
# Enhanced Problem Statement: Django Session Decoding Crash with Invalid Sessions ## Issue Description After upgrading to Django 3.1, the application crashes when trying to process requests containing invalid or corrupted session data. The issue occurs specifically when browsing to any URL with Chrome browser (but not Firefox), making it impossible to log in or access the application. The root cause is Django's session handling mechanism failing to gracefully handle invalid session data. When an invalid session cookie is encountered, Django first attempts to decode it using the signing mechanism, which fails with a `BadSignature` exception. It then falls back to a legacy decoding method that attempts to base64 decode the data without proper validation, resulting in an unhandled `binascii.Error: Incorrect padding` exception that crashes the request processing pipeline. ## Reproduction Steps 1. Upgrade an existing Django application from a previous version to Django 3.1 2. Leave existing sessions in the database (do not clear them) 3. Using Chrome browser that had a session cookie from before the upgrade, attempt to access any URL in the application 4. Observe the server crash with the following error pattern: ``` 1. Django tries to decode the session with signing.loads() 2. BadSignature exception is raised: "Signature does not match" 3. Falls back to _legacy_decode() method 4. binascii.Error occurs: "Incorrect padding" 5. Exception propagates through the middleware stack, crashing the application ``` The error specifically happens in this sequence: 1. Request processing starts and middleware attempts to authenticate user 2. Session data is accessed via `request.session[SESSION_KEY]` 3. This triggers `_get_session` which calls `load()` from the database backend 4. `load()` calls `decode()` on the session data 5. Primary decoding with `signing.loads()` fails with `BadSignature` 6. Fallback to `_legacy_decode()` attempts base64 decoding 7. Base64 decoding fails with `binascii.Error: Incorrect padding` 8. No exception handling exists for this case, causing the crash ## Expected Behavior When encountering an invalid or corrupted session, Django should gracefully handle the exception by: 1. Catching both `BadSignature` and `binascii.Error` exceptions during session decoding 2. Creating a new, empty session when decoding fails completely 3. Continuing with request processing using the fresh session 4. Allowing the user to log in or access the site normally, even with a previously corrupted session ## Exploration Hints ### Files to Examine: - **django/contrib/sessions/backends/base.py** - Contains the core session decoding logic including the `decode()` and `_legacy_decode()` methods that are failing. This file implements the basic session handling framework that all session backends inherit from. - **django/contrib/sessions/backends/db.py** - Implements database-backed sessions with the `load()` method that retrieves session data from the database and attempts to decode it without proper error handling. - **django/core/signing.py** - Contains the cryptographic signing code used for session security; the `loads()` and `TimestampSigner.unsign()` methods are involved in the failure path when trying to validate session signatures. ### Key Classes/Functions: - **SessionBase.decode()** - Responsible for decoding session data; contains a two-step approach that first tries the signing module and falls back to legacy decoding on `BadSignature` error. This method needs improved error handling. - **SessionBase._legacy_decode()** - Attempts base64 decoding of session data without validation, causing the unhandled exception when the data is malformed. - **SessionStore.load()** (in db.py) - Retrieves session from database and calls `decode()` without proper error handling for decode failures. - **signing.loads()** - Validates and decodes signed data; raises `BadSignature` when a session's signature is invalid. ### Areas of Interest: - Exception handling around session decoding is currently insufficient, particularly for base64 decoding errors - Different behavior between browsers suggests possible differences in cookie handling (Chrome vs Firefox) - The upgrade path to Django 3.1 appears to have changed session format or validation without proper migration of existing sessions - Session data flow: browser cookie → middleware → session backend → decode method → application ## Fix Hints ### High Confidence Locations: - **django/contrib/sessions/backends/base.py** - The `_legacy_decode()` method needs to catch `binascii.Error` exceptions and handle them gracefully. - **django/contrib/sessions/backends/base.py** - The `decode()` method should have improved error handling to create a new session when decoding completely fails. ### Implementation Hints: 1. Modify `_legacy_decode()` to wrap the base64 decoding in a try/except block: ```python def _legacy_decode(self, session_data): try: encoded_data = base64.b64decode(session_data.encode('ascii')) # continue with normal decoding except (binascii.Error, UnicodeEncodeError): return {} # Return an empty session on decode failure ``` 2. Enhance the `load()` method in db.py to gracefully handle decode errors: ```python def load(self): try: return self.decode(s.session_data) if s else {} except Exception: # Log the exception but don't crash return {} ``` ### Alternative Hypotheses: 1. **Browser-specific cookie handling** - Chrome might be handling cookies differently than Firefox, potentially truncating or modifying session cookies in a way that causes the base64 padding error. 2. **Proxy server interference** - The nginx proxy mentioned in the report might be modifying or corrupting cookies during request processing. 3. **Session migration issue** - The upgrade to Django 3.1 may have changed session format requirements without properly migrating existing sessions. 4. **Database corruption** - Session data in the database might be corrupted, particularly if the database wasn't properly maintained during the upgrade process. 5. **Middleware interaction** - The error might be related to the interaction between session middleware and other middleware components (like django_otp visible in the traceback), particularly in how they handle authentication state when sessions are invalid.
I tried to run clearsessions, but that didn't help. The only workaround was to delete all rows in the django_session table. Thanks for this report, however I cannot reproduce this issue. Can you provide a sample project? Support for user sessions created by older versions of Django remains until Django 4.0. See similar tickets #31864, #31592, and #31274, this can be a duplicate of one of them. Thanks for the response. It does look similar to the other issues you posted. I don't have a reproducible instance at present. The only way I can think to reproduce would be to start up a 3.0 site, login, wait for the session to expire, then upgrade to 3.1. These are the steps that would have happened on the environment where I encountered the issue. Thanks I was able to reproduce this issue with an invalid session data. Regression in d4fff711d4c97356bd6ba1273d2a5e349326eb5f.
2020-08-18T10:43:52Z
3.2
["test_clear (sessions_tests.tests.CookieSessionTests)", "test_custom_expiry_datetime (sessions_tests.tests.CookieSessionTests)", "test_custom_expiry_reset (sessions_tests.tests.CookieSessionTests)", "test_custom_expiry_seconds (sessions_tests.tests.CookieSessionTests)", "test_custom_expiry_timedelta (sessions_tests.tests.CookieSessionTests)", "test_cycle (sessions_tests.tests.CookieSessionTests)", "test_cycle_with_no_session_cache (sessions_tests.tests.CookieSessionTests)", "test_decode (sessions_tests.tests.CookieSessionTests)", "test_decode_failure_logged_to_security (sessions_tests.tests.CookieSessionTests)", "test_decode_legacy (sessions_tests.tests.CookieSessionTests)", "test_default_expiry (sessions_tests.tests.CookieSessionTests)", "test_default_hashing_algorith_legacy_decode (sessions_tests.tests.CookieSessionTests)", "test_delete (sessions_tests.tests.CookieSessionTests)", "test_flush (sessions_tests.tests.CookieSessionTests)", "test_get_empty (sessions_tests.tests.CookieSessionTests)", "test_get_expire_at_browser_close (sessions_tests.tests.CookieSessionTests)", "test_has_key (sessions_tests.tests.CookieSessionTests)", "test_invalid_key (sessions_tests.tests.CookieSessionTests)", "test_items (sessions_tests.tests.CookieSessionTests)", "test_keys (sessions_tests.tests.CookieSessionTests)", "test_new_session (sessions_tests.tests.CookieSessionTests)", "test_pop (sessions_tests.tests.CookieSessionTests)", "test_pop_default (sessions_tests.tests.CookieSessionTests)", "test_pop_default_named_argument (sessions_tests.tests.CookieSessionTests)", "test_pop_no_default_keyerror_raised (sessions_tests.tests.CookieSessionTests)", "test_save (sessions_tests.tests.CookieSessionTests)", "test_save_doesnt_clear_data (sessions_tests.tests.CookieSessionTests)", "Falsey values (Such as an empty string) are rejected.", "test_session_key_is_read_only (sessions_tests.tests.CookieSessionTests)", "Strings shorter than 8 characters are rejected.", "Strings of length 8 and up are accepted and stored.", "test_setdefault (sessions_tests.tests.CookieSessionTests)", "test_store (sessions_tests.tests.CookieSessionTests)", "test_unpickling_exception (sessions_tests.tests.CookieSessionTests)", "test_update (sessions_tests.tests.CookieSessionTests)", "test_values (sessions_tests.tests.CookieSessionTests)", "test_actual_expiry (sessions_tests.tests.CacheSessionTests)", "test_clear (sessions_tests.tests.CacheSessionTests)", "test_create_and_save (sessions_tests.tests.CacheSessionTests)", "test_custom_expiry_datetime (sessions_tests.tests.CacheSessionTests)", "test_custom_expiry_reset (sessions_tests.tests.CacheSessionTests)", "test_custom_expiry_seconds (sessions_tests.tests.CacheSessionTests)", "test_custom_expiry_timedelta (sessions_tests.tests.CacheSessionTests)", "test_cycle (sessions_tests.tests.CacheSessionTests)", "test_cycle_with_no_session_cache (sessions_tests.tests.CacheSessionTests)", "test_decode (sessions_tests.tests.CacheSessionTests)", "test_decode_failure_logged_to_security (sessions_tests.tests.CacheSessionTests)", "test_decode_legacy (sessions_tests.tests.CacheSessionTests)", "test_default_cache (sessions_tests.tests.CacheSessionTests)", "test_default_expiry (sessions_tests.tests.CacheSessionTests)", "test_default_hashing_algorith_legacy_decode (sessions_tests.tests.CacheSessionTests)", "test_delete (sessions_tests.tests.CacheSessionTests)", "test_flush (sessions_tests.tests.CacheSessionTests)", "test_get_empty (sessions_tests.tests.CacheSessionTests)", "test_get_expire_at_browser_close (sessions_tests.tests.CacheSessionTests)", "test_has_key (sessions_tests.tests.CacheSessionTests)", "test_invalid_key (sessions_tests.tests.CacheSessionTests)", "test_items (sessions_tests.tests.CacheSessionTests)", "test_keys (sessions_tests.tests.CacheSessionTests)", "test_load_overlong_key (sessions_tests.tests.CacheSessionTests)", "test_new_session (sessions_tests.tests.CacheSessionTests)", "test_non_default_cache (sessions_tests.tests.CacheSessionTests)", "test_pop (sessions_tests.tests.CacheSessionTests)", "test_pop_default (sessions_tests.tests.CacheSessionTests)", "test_pop_default_named_argument (sessions_tests.tests.CacheSessionTests)", "test_pop_no_default_keyerror_raised (sessions_tests.tests.CacheSessionTests)", "test_save (sessions_tests.tests.CacheSessionTests)", "test_save_doesnt_clear_data (sessions_tests.tests.CacheSessionTests)", "test_session_key_is_read_only (sessions_tests.tests.CacheSessionTests)", "test_session_load_does_not_create_record (sessions_tests.tests.CacheSessionTests)", "test_session_save_does_not_resurrect_session_logged_out_in_other_context (sessions_tests.tests.CacheSessionTests)", "test_setdefault (sessions_tests.tests.CacheSessionTests)", "test_store (sessions_tests.tests.CacheSessionTests)", "test_update (sessions_tests.tests.CacheSessionTests)", "test_values (sessions_tests.tests.CacheSessionTests)", "test_empty_session_saved (sessions_tests.tests.SessionMiddlewareTests)", "test_flush_empty_without_session_cookie_doesnt_set_cookie (sessions_tests.tests.SessionMiddlewareTests)", "test_httponly_session_cookie (sessions_tests.tests.SessionMiddlewareTests)", "test_no_httponly_session_cookie (sessions_tests.tests.SessionMiddlewareTests)", "test_samesite_session_cookie (sessions_tests.tests.SessionMiddlewareTests)", "test_secure_session_cookie (sessions_tests.tests.SessionMiddlewareTests)", "test_session_delete_on_end (sessions_tests.tests.SessionMiddlewareTests)", "test_session_delete_on_end_with_custom_domain_and_path (sessions_tests.tests.SessionMiddlewareTests)", "test_session_save_on_500 (sessions_tests.tests.SessionMiddlewareTests)", "test_session_update_error_redirect (sessions_tests.tests.SessionMiddlewareTests)", "test_actual_expiry (sessions_tests.tests.FileSessionPathLibTests)", "test_clear (sessions_tests.tests.FileSessionPathLibTests)", "test_clearsessions_command (sessions_tests.tests.FileSessionPathLibTests)", "test_configuration_check (sessions_tests.tests.FileSessionPathLibTests)", "test_custom_expiry_datetime (sessions_tests.tests.FileSessionPathLibTests)", "test_custom_expiry_reset (sessions_tests.tests.FileSessionPathLibTests)", "test_custom_expiry_seconds (sessions_tests.tests.FileSessionPathLibTests)", "test_custom_expiry_timedelta (sessions_tests.tests.FileSessionPathLibTests)", "test_cycle (sessions_tests.tests.FileSessionPathLibTests)", "test_cycle_with_no_session_cache (sessions_tests.tests.FileSessionPathLibTests)", "test_decode (sessions_tests.tests.FileSessionPathLibTests)", "test_decode_failure_logged_to_security (sessions_tests.tests.FileSessionPathLibTests)", "test_decode_legacy (sessions_tests.tests.FileSessionPathLibTests)", "test_default_expiry (sessions_tests.tests.FileSessionPathLibTests)", "test_default_hashing_algorith_legacy_decode (sessions_tests.tests.FileSessionPathLibTests)", "test_delete (sessions_tests.tests.FileSessionPathLibTests)", "test_flush (sessions_tests.tests.FileSessionPathLibTests)", "test_get_empty (sessions_tests.tests.FileSessionPathLibTests)", "test_get_expire_at_browser_close (sessions_tests.tests.FileSessionPathLibTests)", "test_has_key (sessions_tests.tests.FileSessionPathLibTests)", "test_invalid_key (sessions_tests.tests.FileSessionPathLibTests)", "test_invalid_key_backslash (sessions_tests.tests.FileSessionPathLibTests)", "test_invalid_key_forwardslash (sessions_tests.tests.FileSessionPathLibTests)", "test_items (sessions_tests.tests.FileSessionPathLibTests)", "test_keys (sessions_tests.tests.FileSessionPathLibTests)", "test_new_session (sessions_tests.tests.FileSessionPathLibTests)", "test_pop (sessions_tests.tests.FileSessionPathLibTests)", "test_pop_default (sessions_tests.tests.FileSessionPathLibTests)", "test_pop_default_named_argument (sessions_tests.tests.FileSessionPathLibTests)", "test_pop_no_default_keyerror_raised (sessions_tests.tests.FileSessionPathLibTests)", "test_save (sessions_tests.tests.FileSessionPathLibTests)", "test_save_doesnt_clear_data (sessions_tests.tests.FileSessionPathLibTests)", "test_session_key_is_read_only (sessions_tests.tests.FileSessionPathLibTests)", "test_session_load_does_not_create_record (sessions_tests.tests.FileSessionPathLibTests)", "test_session_save_does_not_resurrect_session_logged_out_in_other_context (sessions_tests.tests.FileSessionPathLibTests)", "test_setdefault (sessions_tests.tests.FileSessionPathLibTests)", "test_store (sessions_tests.tests.FileSessionPathLibTests)", "test_update (sessions_tests.tests.FileSessionPathLibTests)", "test_values (sessions_tests.tests.FileSessionPathLibTests)", "test_actual_expiry (sessions_tests.tests.FileSessionTests)", "test_clear (sessions_tests.tests.FileSessionTests)", "test_clearsessions_command (sessions_tests.tests.FileSessionTests)", "test_configuration_check (sessions_tests.tests.FileSessionTests)", "test_custom_expiry_datetime (sessions_tests.tests.FileSessionTests)", "test_custom_expiry_reset (sessions_tests.tests.FileSessionTests)", "test_custom_expiry_seconds (sessions_tests.tests.FileSessionTests)", "test_custom_expiry_timedelta (sessions_tests.tests.FileSessionTests)", "test_cycle (sessions_tests.tests.FileSessionTests)", "test_cycle_with_no_session_cache (sessions_tests.tests.FileSessionTests)", "test_decode (sessions_tests.tests.FileSessionTests)", "test_decode_failure_logged_to_security (sessions_tests.tests.FileSessionTests)", "test_decode_legacy (sessions_tests.tests.FileSessionTests)", "test_default_expiry (sessions_tests.tests.FileSessionTests)", "test_default_hashing_algorith_legacy_decode (sessions_tests.tests.FileSessionTests)", "test_delete (sessions_tests.tests.FileSessionTests)", "test_flush (sessions_tests.tests.FileSessionTests)", "test_get_empty (sessions_tests.tests.FileSessionTests)", "test_get_expire_at_browser_close (sessions_tests.tests.FileSessionTests)", "test_has_key (sessions_tests.tests.FileSessionTests)", "test_invalid_key (sessions_tests.tests.FileSessionTests)", "test_invalid_key_backslash (sessions_tests.tests.FileSessionTests)", "test_invalid_key_forwardslash (sessions_tests.tests.FileSessionTests)", "test_items (sessions_tests.tests.FileSessionTests)", "test_keys (sessions_tests.tests.FileSessionTests)", "test_new_session (sessions_tests.tests.FileSessionTests)", "test_pop (sessions_tests.tests.FileSessionTests)", "test_pop_default (sessions_tests.tests.FileSessionTests)", "test_pop_default_named_argument (sessions_tests.tests.FileSessionTests)", "test_pop_no_default_keyerror_raised (sessions_tests.tests.FileSessionTests)", "test_save (sessions_tests.tests.FileSessionTests)", "test_save_doesnt_clear_data (sessions_tests.tests.FileSessionTests)", "test_session_key_is_read_only (sessions_tests.tests.FileSessionTests)", "test_session_load_does_not_create_record (sessions_tests.tests.FileSessionTests)", "test_session_save_does_not_resurrect_session_logged_out_in_other_context (sessions_tests.tests.FileSessionTests)", "test_setdefault (sessions_tests.tests.FileSessionTests)", "test_store (sessions_tests.tests.FileSessionTests)", "test_update (sessions_tests.tests.FileSessionTests)", "test_values (sessions_tests.tests.FileSessionTests)", "test_actual_expiry (sessions_tests.tests.DatabaseSessionTests)", "test_clear (sessions_tests.tests.DatabaseSessionTests)", "test_clearsessions_command (sessions_tests.tests.DatabaseSessionTests)", "test_custom_expiry_datetime (sessions_tests.tests.DatabaseSessionTests)", "test_custom_expiry_reset (sessions_tests.tests.DatabaseSessionTests)", "test_custom_expiry_seconds (sessions_tests.tests.DatabaseSessionTests)", "test_custom_expiry_timedelta (sessions_tests.tests.DatabaseSessionTests)", "test_cycle (sessions_tests.tests.DatabaseSessionTests)", "test_cycle_with_no_session_cache (sessions_tests.tests.DatabaseSessionTests)", "test_decode (sessions_tests.tests.DatabaseSessionTests)", "test_decode_failure_logged_to_security (sessions_tests.tests.DatabaseSessionTests)", "test_decode_legacy (sessions_tests.tests.DatabaseSessionTests)", "test_default_expiry (sessions_tests.tests.DatabaseSessionTests)", "test_default_hashing_algorith_legacy_decode (sessions_tests.tests.DatabaseSessionTests)", "test_delete (sessions_tests.tests.DatabaseSessionTests)", "test_flush (sessions_tests.tests.DatabaseSessionTests)", "test_get_empty (sessions_tests.tests.DatabaseSessionTests)", "test_get_expire_at_browser_close (sessions_tests.tests.DatabaseSessionTests)", "test_has_key (sessions_tests.tests.DatabaseSessionTests)", "test_invalid_key (sessions_tests.tests.DatabaseSessionTests)", "test_items (sessions_tests.tests.DatabaseSessionTests)", "test_keys (sessions_tests.tests.DatabaseSessionTests)", "test_new_session (sessions_tests.tests.DatabaseSessionTests)", "test_pop (sessions_tests.tests.DatabaseSessionTests)", "test_pop_default (sessions_tests.tests.DatabaseSessionTests)", "test_pop_default_named_argument (sessions_tests.tests.DatabaseSessionTests)", "test_pop_no_default_keyerror_raised (sessions_tests.tests.DatabaseSessionTests)", "test_save (sessions_tests.tests.DatabaseSessionTests)", "test_save_doesnt_clear_data (sessions_tests.tests.DatabaseSessionTests)", "test_session_get_decoded (sessions_tests.tests.DatabaseSessionTests)", "test_session_key_is_read_only (sessions_tests.tests.DatabaseSessionTests)", "test_session_load_does_not_create_record (sessions_tests.tests.DatabaseSessionTests)", "test_session_save_does_not_resurrect_session_logged_out_in_other_context (sessions_tests.tests.DatabaseSessionTests)", "Session repr should be the session key.", "test_sessionmanager_save (sessions_tests.tests.DatabaseSessionTests)", "test_setdefault (sessions_tests.tests.DatabaseSessionTests)", "test_store (sessions_tests.tests.DatabaseSessionTests)", "test_update (sessions_tests.tests.DatabaseSessionTests)", "test_values (sessions_tests.tests.DatabaseSessionTests)", "test_actual_expiry (sessions_tests.tests.CustomDatabaseSessionTests)", "test_clear (sessions_tests.tests.CustomDatabaseSessionTests)", "test_clearsessions_command (sessions_tests.tests.CustomDatabaseSessionTests)", "test_custom_expiry_datetime (sessions_tests.tests.CustomDatabaseSessionTests)", "test_custom_expiry_reset (sessions_tests.tests.CustomDatabaseSessionTests)", "test_custom_expiry_seconds (sessions_tests.tests.CustomDatabaseSessionTests)", "test_custom_expiry_timedelta (sessions_tests.tests.CustomDatabaseSessionTests)", "test_cycle (sessions_tests.tests.CustomDatabaseSessionTests)", "test_cycle_with_no_session_cache (sessions_tests.tests.CustomDatabaseSessionTests)", "test_decode (sessions_tests.tests.CustomDatabaseSessionTests)", "test_decode_failure_logged_to_security (sessions_tests.tests.CustomDatabaseSessionTests)", "test_decode_legacy (sessions_tests.tests.CustomDatabaseSessionTests)", "test_default_expiry (sessions_tests.tests.CustomDatabaseSessionTests)", "test_default_hashing_algorith_legacy_decode (sessions_tests.tests.CustomDatabaseSessionTests)", "test_delete (sessions_tests.tests.CustomDatabaseSessionTests)", "test_extra_session_field (sessions_tests.tests.CustomDatabaseSessionTests)", "test_flush (sessions_tests.tests.CustomDatabaseSessionTests)", "test_get_empty (sessions_tests.tests.CustomDatabaseSessionTests)", "test_get_expire_at_browser_close (sessions_tests.tests.CustomDatabaseSessionTests)", "test_has_key (sessions_tests.tests.CustomDatabaseSessionTests)", "test_invalid_key (sessions_tests.tests.CustomDatabaseSessionTests)", "test_items (sessions_tests.tests.CustomDatabaseSessionTests)", "test_keys (sessions_tests.tests.CustomDatabaseSessionTests)", "test_new_session (sessions_tests.tests.CustomDatabaseSessionTests)", "test_pop (sessions_tests.tests.CustomDatabaseSessionTests)", "test_pop_default (sessions_tests.tests.CustomDatabaseSessionTests)", "test_pop_default_named_argument (sessions_tests.tests.CustomDatabaseSessionTests)", "test_pop_no_default_keyerror_raised (sessions_tests.tests.CustomDatabaseSessionTests)", "test_save (sessions_tests.tests.CustomDatabaseSessionTests)", "test_save_doesnt_clear_data (sessions_tests.tests.CustomDatabaseSessionTests)", "test_session_get_decoded (sessions_tests.tests.CustomDatabaseSessionTests)", "test_session_key_is_read_only (sessions_tests.tests.CustomDatabaseSessionTests)", "test_session_load_does_not_create_record (sessions_tests.tests.CustomDatabaseSessionTests)", "test_session_save_does_not_resurrect_session_logged_out_in_other_context (sessions_tests.tests.CustomDatabaseSessionTests)", "test_sessionmanager_save (sessions_tests.tests.CustomDatabaseSessionTests)", "test_setdefault (sessions_tests.tests.CustomDatabaseSessionTests)", "test_store (sessions_tests.tests.CustomDatabaseSessionTests)", "test_update (sessions_tests.tests.CustomDatabaseSessionTests)", "test_values (sessions_tests.tests.CustomDatabaseSessionTests)", "test_actual_expiry (sessions_tests.tests.CacheDBSessionTests)", "test_clear (sessions_tests.tests.CacheDBSessionTests)", "test_custom_expiry_datetime (sessions_tests.tests.CacheDBSessionTests)", "test_custom_expiry_reset (sessions_tests.tests.CacheDBSessionTests)", "test_custom_expiry_seconds (sessions_tests.tests.CacheDBSessionTests)", "test_custom_expiry_timedelta (sessions_tests.tests.CacheDBSessionTests)", "test_cycle (sessions_tests.tests.CacheDBSessionTests)", "test_cycle_with_no_session_cache (sessions_tests.tests.CacheDBSessionTests)", "test_decode (sessions_tests.tests.CacheDBSessionTests)", "test_decode_failure_logged_to_security (sessions_tests.tests.CacheDBSessionTests)", "test_decode_legacy (sessions_tests.tests.CacheDBSessionTests)", "test_default_expiry (sessions_tests.tests.CacheDBSessionTests)", "test_default_hashing_algorith_legacy_decode (sessions_tests.tests.CacheDBSessionTests)", "test_delete (sessions_tests.tests.CacheDBSessionTests)", "test_exists_searches_cache_first (sessions_tests.tests.CacheDBSessionTests)", "test_flush (sessions_tests.tests.CacheDBSessionTests)", "test_get_empty (sessions_tests.tests.CacheDBSessionTests)", "test_get_expire_at_browser_close (sessions_tests.tests.CacheDBSessionTests)", "test_has_key (sessions_tests.tests.CacheDBSessionTests)", "test_invalid_key (sessions_tests.tests.CacheDBSessionTests)", "test_items (sessions_tests.tests.CacheDBSessionTests)", "test_keys (sessions_tests.tests.CacheDBSessionTests)", "test_load_overlong_key (sessions_tests.tests.CacheDBSessionTests)", "test_new_session (sessions_tests.tests.CacheDBSessionTests)", "test_non_default_cache (sessions_tests.tests.CacheDBSessionTests)", "test_pop (sessions_tests.tests.CacheDBSessionTests)", "test_pop_default (sessions_tests.tests.CacheDBSessionTests)", "test_pop_default_named_argument (sessions_tests.tests.CacheDBSessionTests)", "test_pop_no_default_keyerror_raised (sessions_tests.tests.CacheDBSessionTests)", "test_save (sessions_tests.tests.CacheDBSessionTests)", "test_save_doesnt_clear_data (sessions_tests.tests.CacheDBSessionTests)", "test_session_key_is_read_only (sessions_tests.tests.CacheDBSessionTests)", "test_session_load_does_not_create_record (sessions_tests.tests.CacheDBSessionTests)", "test_session_save_does_not_resurrect_session_logged_out_in_other_context (sessions_tests.tests.CacheDBSessionTests)", "test_setdefault (sessions_tests.tests.CacheDBSessionTests)", "test_store (sessions_tests.tests.CacheDBSessionTests)", "test_update (sessions_tests.tests.CacheDBSessionTests)", "test_values (sessions_tests.tests.CacheDBSessionTests)", "test_actual_expiry (sessions_tests.tests.CacheDBSessionWithTimeZoneTests)", "test_clear (sessions_tests.tests.CacheDBSessionWithTimeZoneTests)", "test_custom_expiry_datetime (sessions_tests.tests.CacheDBSessionWithTimeZoneTests)", "test_custom_expiry_reset (sessions_tests.tests.CacheDBSessionWithTimeZoneTests)", "test_custom_expiry_seconds (sessions_tests.tests.CacheDBSessionWithTimeZoneTests)", "test_custom_expiry_timedelta (sessions_tests.tests.CacheDBSessionWithTimeZoneTests)", "test_cycle (sessions_tests.tests.CacheDBSessionWithTimeZoneTests)", "test_cycle_with_no_session_cache (sessions_tests.tests.CacheDBSessionWithTimeZoneTests)", "test_decode (sessions_tests.tests.CacheDBSessionWithTimeZoneTests)", "test_decode_failure_logged_to_security (sessions_tests.tests.CacheDBSessionWithTimeZoneTests)", "test_decode_legacy (sessions_tests.tests.CacheDBSessionWithTimeZoneTests)", "test_default_expiry (sessions_tests.tests.CacheDBSessionWithTimeZoneTests)", "test_default_hashing_algorith_legacy_decode (sessions_tests.tests.CacheDBSessionWithTimeZoneTests)", "test_delete (sessions_tests.tests.CacheDBSessionWithTimeZoneTests)", "test_exists_searches_cache_first (sessions_tests.tests.CacheDBSessionWithTimeZoneTests)", "test_flush (sessions_tests.tests.CacheDBSessionWithTimeZoneTests)", "test_get_empty (sessions_tests.tests.CacheDBSessionWithTimeZoneTests)", "test_get_expire_at_browser_close (sessions_tests.tests.CacheDBSessionWithTimeZoneTests)", "test_has_key (sessions_tests.tests.CacheDBSessionWithTimeZoneTests)", "test_invalid_key (sessions_tests.tests.CacheDBSessionWithTimeZoneTests)", "test_items (sessions_tests.tests.CacheDBSessionWithTimeZoneTests)", "test_keys (sessions_tests.tests.CacheDBSessionWithTimeZoneTests)", "test_load_overlong_key (sessions_tests.tests.CacheDBSessionWithTimeZoneTests)", "test_new_session (sessions_tests.tests.CacheDBSessionWithTimeZoneTests)", "test_non_default_cache (sessions_tests.tests.CacheDBSessionWithTimeZoneTests)", "test_pop (sessions_tests.tests.CacheDBSessionWithTimeZoneTests)", "test_pop_default (sessions_tests.tests.CacheDBSessionWithTimeZoneTests)", "test_pop_default_named_argument (sessions_tests.tests.CacheDBSessionWithTimeZoneTests)", "test_pop_no_default_keyerror_raised (sessions_tests.tests.CacheDBSessionWithTimeZoneTests)", "test_save (sessions_tests.tests.CacheDBSessionWithTimeZoneTests)", "test_save_doesnt_clear_data (sessions_tests.tests.CacheDBSessionWithTimeZoneTests)", "test_session_key_is_read_only (sessions_tests.tests.CacheDBSessionWithTimeZoneTests)", "test_session_load_does_not_create_record (sessions_tests.tests.CacheDBSessionWithTimeZoneTests)", "test_session_save_does_not_resurrect_session_logged_out_in_other_context (sessions_tests.tests.CacheDBSessionWithTimeZoneTests)", "test_setdefault (sessions_tests.tests.CacheDBSessionWithTimeZoneTests)", "test_store (sessions_tests.tests.CacheDBSessionWithTimeZoneTests)", "test_update (sessions_tests.tests.CacheDBSessionWithTimeZoneTests)", "test_values (sessions_tests.tests.CacheDBSessionWithTimeZoneTests)", "test_actual_expiry (sessions_tests.tests.DatabaseSessionWithTimeZoneTests)", "test_clear (sessions_tests.tests.DatabaseSessionWithTimeZoneTests)", "test_clearsessions_command (sessions_tests.tests.DatabaseSessionWithTimeZoneTests)", "test_custom_expiry_datetime (sessions_tests.tests.DatabaseSessionWithTimeZoneTests)", "test_custom_expiry_reset (sessions_tests.tests.DatabaseSessionWithTimeZoneTests)", "test_custom_expiry_seconds (sessions_tests.tests.DatabaseSessionWithTimeZoneTests)", "test_custom_expiry_timedelta (sessions_tests.tests.DatabaseSessionWithTimeZoneTests)", "test_cycle (sessions_tests.tests.DatabaseSessionWithTimeZoneTests)", "test_cycle_with_no_session_cache (sessions_tests.tests.DatabaseSessionWithTimeZoneTests)", "test_decode (sessions_tests.tests.DatabaseSessionWithTimeZoneTests)", "test_decode_failure_logged_to_security (sessions_tests.tests.DatabaseSessionWithTimeZoneTests)", "test_decode_legacy (sessions_tests.tests.DatabaseSessionWithTimeZoneTests)", "test_default_expiry (sessions_tests.tests.DatabaseSessionWithTimeZoneTests)", "test_default_hashing_algorith_legacy_decode (sessions_tests.tests.DatabaseSessionWithTimeZoneTests)", "test_delete (sessions_tests.tests.DatabaseSessionWithTimeZoneTests)", "test_flush (sessions_tests.tests.DatabaseSessionWithTimeZoneTests)", "test_get_empty (sessions_tests.tests.DatabaseSessionWithTimeZoneTests)", "test_get_expire_at_browser_close (sessions_tests.tests.DatabaseSessionWithTimeZoneTests)", "test_has_key (sessions_tests.tests.DatabaseSessionWithTimeZoneTests)", "test_invalid_key (sessions_tests.tests.DatabaseSessionWithTimeZoneTests)", "test_items (sessions_tests.tests.DatabaseSessionWithTimeZoneTests)", "test_keys (sessions_tests.tests.DatabaseSessionWithTimeZoneTests)", "test_new_session (sessions_tests.tests.DatabaseSessionWithTimeZoneTests)", "test_pop (sessions_tests.tests.DatabaseSessionWithTimeZoneTests)", "test_pop_default (sessions_tests.tests.DatabaseSessionWithTimeZoneTests)", "test_pop_default_named_argument (sessions_tests.tests.DatabaseSessionWithTimeZoneTests)", "test_pop_no_default_keyerror_raised (sessions_tests.tests.DatabaseSessionWithTimeZoneTests)", "test_save (sessions_tests.tests.DatabaseSessionWithTimeZoneTests)", "test_save_doesnt_clear_data (sessions_tests.tests.DatabaseSessionWithTimeZoneTests)", "test_session_get_decoded (sessions_tests.tests.DatabaseSessionWithTimeZoneTests)", "test_session_key_is_read_only (sessions_tests.tests.DatabaseSessionWithTimeZoneTests)", "test_session_load_does_not_create_record (sessions_tests.tests.DatabaseSessionWithTimeZoneTests)", "test_session_save_does_not_resurrect_session_logged_out_in_other_context (sessions_tests.tests.DatabaseSessionWithTimeZoneTests)", "test_sessionmanager_save (sessions_tests.tests.DatabaseSessionWithTimeZoneTests)", "test_setdefault (sessions_tests.tests.DatabaseSessionWithTimeZoneTests)", "test_store (sessions_tests.tests.DatabaseSessionWithTimeZoneTests)", "test_update (sessions_tests.tests.DatabaseSessionWithTimeZoneTests)", "test_values (sessions_tests.tests.DatabaseSessionWithTimeZoneTests)"]
[]
65dfb06a1ab56c238cc80f5e1c31f61210c4577d
django/django
django__django-12908
49ae7ce50a874f8a04cd910882fb9571ff3a0d7a
diff --git a/django/db/models/query.py b/django/db/models/query.py --- a/django/db/models/query.py +++ b/django/db/models/query.py @@ -1138,6 +1138,7 @@ def distinct(self, *field_names): """ Return a new QuerySet instance that will select only distinct results. """ + self._not_support_combined_queries('distinct') assert not self.query.is_sliced, \ "Cannot create distinct fields once a slice has been taken." obj = self._chain()
diff --git a/tests/queries/test_qs_combinators.py b/tests/queries/test_qs_combinators.py --- a/tests/queries/test_qs_combinators.py +++ b/tests/queries/test_qs_combinators.py @@ -272,6 +272,7 @@ def test_unsupported_operations_on_combined_qs(self): 'annotate', 'defer', 'delete', + 'distinct', 'exclude', 'extra', 'filter',
# Enhanced Problem Statement: DISTINCT ON Not Working with UNION Queryset ## Issue Description When applying `.distinct()` with field arguments (e.g., `.distinct('name')`) on a queryset that is the result of a `.union()` operation on annotated querysets, the distinct operation is not properly applied to the combined results. This occurs because the SQL compiler does not correctly wrap the UNION query in a subquery before applying the DISTINCT ON clause. Instead of generating SQL that applies DISTINCT ON to the outer query wrapping the union, the operation appears to be ignored or improperly applied to the individual parts of the union. This issue specifically affects PostgreSQL's DISTINCT ON functionality. ## Reproduction Steps ```python def setUp(self) -> None: user = self.get_or_create_admin_user() Sample.h.create(user, name="Sam1") Sample.h.create(user, name="Sam2 acid") Sample.h.create(user, name="Sam3") Sample.h.create(user, name="Sam4 acid") Sample.h.create(user, name="Dub") Sample.h.create(user, name="Dub") Sample.h.create(user, name="Dub") self.user = user def test_union_annotated_diff_distinct(self): qs = Sample.objects.filter(user=self.user) qs1 = qs.filter(name='Dub').annotate(rank=Value(0, IntegerField())) qs2 = qs.filter(name='Sam1').annotate(rank=Value(1, IntegerField())) qs = qs1.union(qs2) qs = qs.order_by('name').distinct('name') # THIS DISTINCT DOESN'T WORK self.assertEqual(qs.count(), 2) # This fails because distinct is not effective ``` Internally, what happens is: 1. Two querysets are created with annotations 2. The querysets are combined with `union()` 3. The `distinct('name')` operation is applied to the combined queryset 4. When the SQL is compiled, the DISTINCT ON clause is not properly applied to the outer query wrapping the union The expected SQL should be: ```sql SELECT DISTINCT ON (siebox_sample.name) * FROM (SELECT ... UNION SELECT ...) AS siebox_sample ``` But the generated SQL doesn't correctly wrap the DISTINCT ON around the union result, causing the distinct operation to be ineffective. ## Expected Behavior When calling `.distinct('name')` on a unioned queryset, Django should generate SQL that applies the DISTINCT ON clause to the outer query that wraps the union operation. The final SQL should have the form: ```sql SELECT DISTINCT ON (table_alias.name) * FROM (SELECT ... UNION SELECT ...) AS table_alias ``` This would ensure that the distinct operation correctly filters rows with duplicate name values from the combined result set, resulting in exactly 2 records in the example test case. ## Exploration Hints ### Files to Examine: - **django/db/models/query.py** - Contains the `QuerySet` class with the `union()` and `distinct()` methods. The issue involves how these methods interact and how the resulting query structure is built. - **django/db/models/sql/compiler.py** - Contains the SQL compilation logic that transforms Django ORM queries into actual SQL statements. The bug is likely in how the compiler handles distinct operations on union querysets. - **django/db/backends/postgresql/operations.py** - Contains PostgreSQL-specific operations, including how DISTINCT ON queries are handled. The issue is specific to PostgreSQL's DISTINCT ON feature. ### Key Classes/Functions: - **QuerySet._combinator_query()** - Handles the logic for combining querysets using SQL combinators like UNION. Needs examination to see how it preserves the ability to apply post-union operations. - **QuerySet.distinct()** - Adds distinct fields to the query, but might not be properly interacting with combined queries. - **SQLCompiler.get_distinct()** - Responsible for generating the DISTINCT part of the SQL query. May not handle union querysets correctly. - **SQLCompiler.get_combinator_sql()** - Handles SQL generation for combinator operations like UNION. May not preserve distinct operations. - **DatabaseOperations.distinct_sql** (PostgreSQL backend) - Generates PostgreSQL-specific DISTINCT ON syntax. May need adjustments for union queries. ### Areas of Interest: - How query combination operations (like union) create composite query structures - How distinct operations are propagated through the query compilation process - The interaction between annotation, union, and distinct operations - How PostgreSQL's DISTINCT ON syntax is handled differently from regular DISTINCT - The ordering of operations during SQL compilation when both UNION and DISTINCT are present ## Fix Hints ### High Confidence Locations: - **SQLCompiler.get_combinator_sql()** method - This method generates SQL for UNION and other combinators, but likely doesn't properly handle subsequent operations like distinct. It needs to be modified to ensure that operations like DISTINCT ON are applied to the outer query wrapping the union. ### Implementation Hints: - The fix likely involves restructuring how combined queries are wrapped during SQL compilation - When a distinct operation is detected on a combined query, the SQL compiler needs to ensure it wraps the union result in a subquery before applying the DISTINCT ON clause - May require changes to how table aliases are managed when applying distinct to a union query - Consider refactoring the query compilation process to better separate the stages of union query generation and application of operations like distinct ### Alternative Hypotheses: - The issue might be in the query's `combine()` method rather than in the SQL compiler, as it may not properly preserve distinct flags when combining queries - The problem could be specific to how field references work in the context of a union query with annotations, causing the distinct operation to target the wrong fields - It's possible that there's a deeper architectural issue with how Django handles complex query combinations, where certain operation orderings aren't fully supported The most likely solution involves modifying the SQL compiler to ensure that DISTINCT ON operations are applied as an outer wrapper around UNION queries rather than trying to incorporate them into the individual queries being united.
distinct() is not supported but doesn't raise an error yet. As ​​per the documentation, "only LIMIT, OFFSET, COUNT(*), ORDER BY, and specifying columns (i.e. slicing, count(), order_by(), and values()/values_list()) are allowed on the resulting QuerySet.". Follow up to #27995.
2020-05-13T11:36:48Z
3.2
["test_unsupported_operations_on_combined_qs (queries.test_qs_combinators.QuerySetSetOperationTests)", "test_unsupported_ordering_slicing_raises_db_error (queries.test_qs_combinators.QuerySetSetOperationTests)"]
["test_combining_multiple_models (queries.test_qs_combinators.QuerySetSetOperationTests)", "test_count_difference (queries.test_qs_combinators.QuerySetSetOperationTests)", "test_count_intersection (queries.test_qs_combinators.QuerySetSetOperationTests)", "test_count_union (queries.test_qs_combinators.QuerySetSetOperationTests)", "test_count_union_empty_result (queries.test_qs_combinators.QuerySetSetOperationTests)", "test_difference_with_empty_qs (queries.test_qs_combinators.QuerySetSetOperationTests)", "test_difference_with_values (queries.test_qs_combinators.QuerySetSetOperationTests)", "test_intersection_with_empty_qs (queries.test_qs_combinators.QuerySetSetOperationTests)", "test_intersection_with_values (queries.test_qs_combinators.QuerySetSetOperationTests)", "test_limits (queries.test_qs_combinators.QuerySetSetOperationTests)", "test_order_by_same_type (queries.test_qs_combinators.QuerySetSetOperationTests)", "test_order_raises_on_non_selected_column (queries.test_qs_combinators.QuerySetSetOperationTests)", "test_ordering (queries.test_qs_combinators.QuerySetSetOperationTests)", "test_ordering_by_f_expression (queries.test_qs_combinators.QuerySetSetOperationTests)", "test_qs_with_subcompound_qs (queries.test_qs_combinators.QuerySetSetOperationTests)", "test_simple_difference (queries.test_qs_combinators.QuerySetSetOperationTests)", "test_simple_intersection (queries.test_qs_combinators.QuerySetSetOperationTests)", "test_simple_union (queries.test_qs_combinators.QuerySetSetOperationTests)", "test_union_distinct (queries.test_qs_combinators.QuerySetSetOperationTests)", "test_union_with_empty_qs (queries.test_qs_combinators.QuerySetSetOperationTests)", "test_union_with_extra_and_values_list (queries.test_qs_combinators.QuerySetSetOperationTests)", "test_union_with_two_annotated_values_list (queries.test_qs_combinators.QuerySetSetOperationTests)", "test_union_with_values (queries.test_qs_combinators.QuerySetSetOperationTests)", "test_union_with_values_list_and_order (queries.test_qs_combinators.QuerySetSetOperationTests)", "test_union_with_values_list_on_annotated_and_unannotated (queries.test_qs_combinators.QuerySetSetOperationTests)"]
65dfb06a1ab56c238cc80f5e1c31f61210c4577d
End of preview. Expand in Data Studio
README.md exists but content is empty.
Downloads last month
1