Skip to content

Fix QuerySet.raw_aggregate() when document key order differs from model field order #274

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Mar 25, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion django_mongodb_backend/queryset.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,4 +93,4 @@ def _make_result(self, query):
of __iter__().
"""
for result in query:
yield tuple(result.values())
yield tuple(result.get(key) for key in self.queryset.columns)
2 changes: 2 additions & 0 deletions docs/source/releases/5.1.x.rst
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ Django MongoDB Backend 5.1.x
*Unreleased*

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

5.1.0 beta 1
============
Expand Down
20 changes: 19 additions & 1 deletion tests/raw_query_/test_raw_aggregate.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,10 @@
These tests are adapted from Django's tests/raw_query/tests.py.
"""

from datetime import date
from datetime import date, datetime

from django.core.exceptions import FieldDoesNotExist
from django.db import connection
from django.test import TestCase

from django_mongodb_backend.queryset import RawQuerySet
Expand Down Expand Up @@ -170,6 +171,23 @@ def test_order_handler(self):
authors = Author.objects.all()
self.assertSuccessfulRawQuery(Author, query, authors)

def test_different_db_key_order(self):
"""
A raw query correctly associates document keys to model fields when the
document key order is different than the order of model fields.
"""
author = Author(first_name="Out of", last_name="Order", dob=datetime(1950, 9, 20))
# Insert a document with the keys reversed.
connection.database.get_collection(Author._meta.db_table).insert_one(
{
field.name: getattr(author, field.name)
for field in reversed(Author._meta.concrete_fields)
}
)
query = []
authors = Author.objects.all()
self.assertSuccessfulRawQuery(Author, query, authors)

def test_query_representation(self):
"""Test representation of raw query."""
query = [{"$match": {"last_name": "foo"}}]
Expand Down
Loading