diff --git a/django/db/models/query.py b/django/db/models/query.py index ae0b44cf2a..9fd116c4a6 100644 --- a/django/db/models/query.py +++ b/django/db/models/query.py @@ -1159,10 +1159,11 @@ class RawQuerySet: def resolve_model_init_order(self): """Resolve the init field names and value positions.""" - model_init_fields = [f for f in self.model._meta.fields if f.column in self.columns] + converter = connections[self.db].introspection.column_name_converter + model_init_fields = [f for f in self.model._meta.fields if converter(f.column) in self.columns] annotation_fields = [(column, pos) for pos, column in enumerate(self.columns) if column not in self.model_fields] - model_init_order = [self.columns.index(f.column) for f in model_init_fields] + model_init_order = [self.columns.index(converter(f.column)) for f in model_init_fields] model_init_names = [f.attname for f in model_init_fields] return model_init_names, model_init_order, annotation_fields diff --git a/tests/raw_query/models.py b/tests/raw_query/models.py index 7e090b7a3f..f0e6c3abb2 100644 --- a/tests/raw_query/models.py +++ b/tests/raw_query/models.py @@ -32,6 +32,10 @@ class Coffee(models.Model): price = models.DecimalField(max_digits=10, decimal_places=2, default=0) +class MixedCaseIDColumn(models.Model): + id = models.AutoField(primary_key=True, db_column='MiXeD_CaSe_Id') + + class Reviewer(models.Model): reviewed = models.ManyToManyField(Book) diff --git a/tests/raw_query/tests.py b/tests/raw_query/tests.py index 26b57dc139..bcc075ea35 100644 --- a/tests/raw_query/tests.py +++ b/tests/raw_query/tests.py @@ -5,7 +5,10 @@ from django.db.models.query import RawQuerySet from django.db.models.query_utils import InvalidQuery from django.test import TestCase, skipUnlessDBFeature -from .models import Author, Book, BookFkAsPk, Coffee, FriendlyAuthor, Reviewer +from .models import ( + Author, Book, BookFkAsPk, Coffee, FriendlyAuthor, MixedCaseIDColumn, + Reviewer, +) class RawQueryTests(TestCase): @@ -129,6 +132,14 @@ class RawQueryTests(TestCase): coffees = Coffee.objects.all() self.assertSuccessfulRawQuery(Coffee, query, coffees) + def test_pk_with_mixed_case_db_column(self): + """ + A raw query with a model that has a pk db_column with mixed case. + """ + query = "SELECT * FROM raw_query_mixedcaseidcolumn" + queryset = MixedCaseIDColumn.objects.all() + self.assertSuccessfulRawQuery(MixedCaseIDColumn, query, queryset) + def test_order_handler(self): """ Test of raw raw query's tolerance for columns being returned in any