Skip to content

Commit

Permalink
Merge branch 'main' into partial-indexes
Browse files Browse the repository at this point in the history
  • Loading branch information
WaVEV authored Oct 31, 2024
2 parents 99623ee + a06efe3 commit 7a03e3a
Show file tree
Hide file tree
Showing 7 changed files with 78 additions and 5 deletions.
1 change: 1 addition & 0 deletions .github/workflows/test-python.yml
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,7 @@ jobs:
migrations
model_fields
model_forms
model_formsets
model_inheritance_regress
mutually_referential
nested_foreign_keys
Expand Down
24 changes: 19 additions & 5 deletions django_mongodb/fields/auto.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,14 @@ def __init__(self, *args, **kwargs):
kwargs["db_column"] = "_id"
super().__init__(*args, **kwargs)

def deconstruct(self):
name, path, args, kwargs = super().deconstruct()
if self.db_column == "_id":
del kwargs["db_column"]
if path.startswith("django_mongodb.fields.auto"):
path = path.replace("django_mongodb.fields.auto", "django_mongodb.fields")
return name, path, args, kwargs

def get_prep_value(self, value):
if value is None:
return None
Expand All @@ -34,17 +42,23 @@ def get_prep_value(self, value):
def db_type(self, connection):
return "objectId"

def rel_db_type(self, connection):
return "objectId"

def to_python(self, value):
if value is None or isinstance(value, int):
return value
try:
return ObjectId(value)
except errors.InvalidId:
raise exceptions.ValidationError(
self.error_messages["invalid"],
code="invalid",
params={"value": value},
) from None
try:
return int(value)
except ValueError:
raise exceptions.ValidationError(
self.error_messages["invalid"],
code="invalid",
params={"value": value},
) from None

@cached_property
def validators(self):
Expand Down
Empty file added tests/model_fields_/__init__.py
Empty file.
16 changes: 16 additions & 0 deletions tests/model_fields_/test_autofield.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
from django.test import SimpleTestCase

from django_mongodb.fields import ObjectIdAutoField


class MethodTests(SimpleTestCase):
def test_deconstruct(self):
field = ObjectIdAutoField()
name, path, args, kwargs = field.deconstruct()
self.assertEqual(path, "django_mongodb.fields.ObjectIdAutoField")
self.assertEqual(args, [])
self.assertEqual(kwargs, {"primary_key": True})

def test_to_python(self):
f = ObjectIdAutoField()
self.assertEqual(f.to_python("1"), 1)
Empty file added tests/queries_/__init__.py
Empty file.
16 changes: 16 additions & 0 deletions tests/queries_/models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
from django.db import models


class Author(models.Model):
name = models.CharField(max_length=10)

def __str__(self):
return self.name


class Book(models.Model):
title = models.CharField(max_length=10)
author = models.ForeignKey(Author, models.CASCADE)

def __str__(self):
return self.title
26 changes: 26 additions & 0 deletions tests/queries_/test_mql.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
from django.test import TestCase

from .models import Author, Book


class MQLTests(TestCase):
def test_all(self):
with self.assertNumQueries(1) as ctx:
list(Author.objects.all())
query = ctx.captured_queries[0]["sql"]
self.assertEqual(query, "db.queries__author.aggregate([{'$match': {'$expr': {}}}])")

def test_join(self):
with self.assertNumQueries(1) as ctx:
list(Book.objects.filter(author__name="Bob"))
query = ctx.captured_queries[0]["sql"]
self.assertEqual(
query,
"db.queries__book.aggregate(["
"{'$lookup': {'from': 'queries__author', "
"'let': {'parent__field__0': '$author_id'}, "
"'pipeline': [{'$match': {'$expr': "
"{'$and': [{'$eq': ['$$parent__field__0', '$_id']}]}}}], 'as': 'queries__author'}}, "
"{'$unwind': '$queries__author'}, "
"{'$match': {'$expr': {'$eq': ['$queries__author.name', 'Bob']}}}])",
)

0 comments on commit 7a03e3a

Please sign in to comment.