Skip to content

Commit 5ab4f6e

Browse files
Jibolatimgraham
authored andcommitted
Fix QuerySet.raw_aggregate() when document key order differs from model field order
1 parent 51b6b07 commit 5ab4f6e

File tree

3 files changed

+22
-2
lines changed

3 files changed

+22
-2
lines changed

django_mongodb_backend/queryset.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -93,4 +93,4 @@ def _make_result(self, query):
9393
of __iter__().
9494
"""
9595
for result in query:
96-
yield tuple(result.values())
96+
yield tuple(result.get(key) for key in self.queryset.columns)

docs/source/releases/5.1.x.rst

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,8 @@ Django MongoDB Backend 5.1.x
88
*Unreleased*
99

1010
- Added support for :doc:`database caching </topics/cache>`.
11+
- Fixed ``QuerySet.raw_aggregate()`` field initialization when the document key
12+
order doesn't match the order of the model's fields.
1113

1214
5.1.0 beta 1
1315
============

tests/raw_query_/test_raw_aggregate.py

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,10 @@
22
These tests are adapted from Django's tests/raw_query/tests.py.
33
"""
44

5-
from datetime import date
5+
from datetime import date, datetime
66

77
from django.core.exceptions import FieldDoesNotExist
8+
from django.db import connection
89
from django.test import TestCase
910

1011
from django_mongodb_backend.queryset import RawQuerySet
@@ -170,6 +171,23 @@ def test_order_handler(self):
170171
authors = Author.objects.all()
171172
self.assertSuccessfulRawQuery(Author, query, authors)
172173

174+
def test_different_db_key_order(self):
175+
"""
176+
A raw query correctly associates document keys to model fields when the
177+
document key order is different than the order of model fields.
178+
"""
179+
author = Author(first_name="Out of", last_name="Order", dob=datetime(1950, 9, 20))
180+
# Insert a document with the keys reversed.
181+
connection.database.get_collection(Author._meta.db_table).insert_one(
182+
{
183+
field.name: getattr(author, field.name)
184+
for field in reversed(Author._meta.concrete_fields)
185+
}
186+
)
187+
query = []
188+
authors = Author.objects.all()
189+
self.assertSuccessfulRawQuery(Author, query, authors)
190+
173191
def test_query_representation(self):
174192
"""Test representation of raw query."""
175193
query = [{"$match": {"last_name": "foo"}}]

0 commit comments

Comments
 (0)