Skip to content

Commit

Permalink
192: Add support to hash objects that are not Django models
Browse files Browse the repository at this point in the history
  • Loading branch information
MartinGotelli committed Nov 5, 2024
1 parent 40ad77d commit 825011b
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 0 deletions.
4 changes: 4 additions & 0 deletions django_mock_queries/utils.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from datetime import datetime, date
from django.core.exceptions import FieldError
from django.db import models
from django.db.models import F, Value, Case
from django.db.models.functions import Coalesce
from unittest.mock import Mock
Expand Down Expand Up @@ -304,6 +305,9 @@ def truncate(obj, kind):


def hash_dict(obj, *fields):
if not isinstance(obj, models.Model):
return hash(obj)

field_names = fields or find_field_names(obj, concrete_only=True)[1]
obj_values = {f: get_field_value(obj, f) for f in field_names}

Expand Down
19 changes: 19 additions & 0 deletions tests/test_mocks.py
Original file line number Diff line number Diff line change
Expand Up @@ -587,3 +587,22 @@ def test_model_mocker_does_not_interfere_with_non_mocked_models(self):

with self.assertRaises(NotSupportedError):
CarVariation.objects.all().delete()

def test_distinct_for_flat_values(self):
with ModelMocker(Manufacturer):
toyota = Manufacturer.objects.create(name="Toyota")
ford = Manufacturer.objects.create(name="Ford")
distinct_names = Manufacturer.objects.values_list("name", flat=True).distinct()
assert list(distinct_names) == [toyota.name, ford.name]

def test_distinct_for_objects(self):
with ModelMocker(Manufacturer):
toyota = Manufacturer.objects.create(name="Toyota")
ford = Manufacturer.objects.create(name="Ford")
ford_2 = Manufacturer.objects.create(name="Ford")
distinct_objects = Manufacturer.objects.distinct()
assert list(distinct_objects) == [toyota, ford, ford_2]
distinct_objects = Manufacturer.objects.distinct("name")
assert list(distinct_objects) == [toyota, ford]
distinct_objects = Manufacturer.objects.distinct("id")
assert list(distinct_objects) == [toyota, ford, ford_2]

0 comments on commit 825011b

Please sign in to comment.