Skip to content

Commit

Permalink
fix: Do not include annotation fields when selecting specific fields (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
devxoul committed May 4, 2022
1 parent f5264aa commit defc37c
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 3 deletions.
9 changes: 6 additions & 3 deletions modeltranslation/manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -414,8 +414,9 @@ def raw_values(self, *fields):
def _values(self, *original, **kwargs):
if not kwargs.pop('prepare', False):
return super(MultilingualQuerySet, self)._values(*original, **kwargs)
selects_all = kwargs.pop('selects_all', False)
new_fields, translation_fields = append_fallback(self.model, original)
annotation_keys = set(self.query.annotation_select.keys())
annotation_keys = set(self.query.annotation_select.keys()) if selects_all else set()
new_fields.update(annotation_keys)
clone = super(MultilingualQuerySet, self)._values(*list(new_fields), **kwargs)
clone.original_fields = tuple(original)
Expand All @@ -427,10 +428,11 @@ def _values(self, *original, **kwargs):
def values(self, *fields, **expressions):
if not self._rewrite:
return super(MultilingualQuerySet, self).values(*fields, **expressions)
selects_all = not fields
if not fields:
# Emulate original queryset behaviour: get all fields that are not translation fields
fields = self._get_original_fields()
clone = self._values(*fields, prepare=True, **expressions)
clone = self._values(*fields, prepare=True, selects_all=selects_all, **expressions)
clone._iterable_class = FallbackValuesIterable
return clone

Expand All @@ -445,10 +447,11 @@ def values_list(self, *fields, **kwargs):
raise TypeError(
"'flat' is not valid when values_list is " "called with more than one field."
)
selects_all = not fields
if not fields:
# Emulate original queryset behaviour: get all fields that are not translation fields
fields = self._get_original_fields()
clone = self._values(*fields, prepare=True)
clone = self._values(*fields, prepare=True, selects_all=selects_all)
clone._iterable_class = (
FallbackFlatValuesListIterable if flat else FallbackValuesListIterable
)
Expand Down
11 changes: 11 additions & 0 deletions modeltranslation/tests/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -2919,6 +2919,17 @@ def test_values(self):
id1,
)

# custom annotation with fields specified
self.assertEqual(
list(manager.filter(id=id1).annotate(custom_id=F('id')).values_list('id'))[0],
(id1,),
)
self.assertIsNone(
list(manager.filter(id=id1).annotate(custom_id=F('id')).values('id'))[0].get(
'custom_id'
),
)

def test_values_list_annotation(self):
models.TestModel(title='foo').save()
models.TestModel(title='foo').save()
Expand Down

0 comments on commit defc37c

Please sign in to comment.