|
| 1 | +from django.db.models.query import BaseIterable |
| 2 | +from garnett.expressions import L |
| 3 | + |
| 4 | +PREFIX = "L_garnett__" |
| 5 | + |
| 6 | + |
| 7 | +class TranslatableValuesIterable(BaseIterable): |
| 8 | + """ |
| 9 | + Unwind the modifications that are made before calling .values() |
| 10 | + Iterable returned by QuerySet.values() that yields a dict for each row. |
| 11 | + """ |
| 12 | + |
| 13 | + def clean_garnett_field(self, field_name) -> str: |
| 14 | + """Return the field name minus the prefix""" |
| 15 | + return field_name.replace(PREFIX, "") |
| 16 | + |
| 17 | + def __iter__(self): |
| 18 | + queryset = self.queryset |
| 19 | + query = queryset.query |
| 20 | + compiler = query.get_compiler(queryset.db) |
| 21 | + |
| 22 | + # extra(select=...) cols are always at the start of the row. |
| 23 | + names = [ |
| 24 | + *query.extra_select, |
| 25 | + *query.values_select, |
| 26 | + *query.annotation_select, |
| 27 | + ] |
| 28 | + indexes = range(len(names)) |
| 29 | + for row in compiler.results_iter( |
| 30 | + chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size |
| 31 | + ): |
| 32 | + yield {self.clean_garnett_field(names[i]): row[i] for i in indexes} |
| 33 | + |
| 34 | + |
| 35 | +class TranslatedQuerySetMixin: |
| 36 | + """ |
| 37 | + A translated QuerySet mixin to add extra functionality to translated fields |
| 38 | + Must be mixedin to a QuerySet |
| 39 | + """ |
| 40 | + |
| 41 | + def values(self, *fields, **expressions): |
| 42 | + """ |
| 43 | + .values() for translatable fields |
| 44 | + Still expects values to be passed with L() |
| 45 | + """ |
| 46 | + |
| 47 | + # Convert anything that is an L from a field to an expression - so it treats it as an expression |
| 48 | + # rather than a field. |
| 49 | + # We will clean the field prefix in our custom iterable class "TranslatableQuerySetMixin" |
| 50 | + cleaned_fields = [] |
| 51 | + for field in fields: |
| 52 | + if isinstance(field, L): |
| 53 | + expressions.update( |
| 54 | + {f"{PREFIX}{field.source_expressions[0].name}": field} |
| 55 | + ) |
| 56 | + else: |
| 57 | + cleaned_fields.append(field) |
| 58 | + |
| 59 | + clone = super().values(*cleaned_fields, **expressions) |
| 60 | + clone._iterable_class = TranslatableValuesIterable |
| 61 | + |
| 62 | + return clone |
0 commit comments