Object that handles combinations of .only() and .exclude() calls
| 2 | |
| 3 | |
| 4 | class QueryFieldList: |
| 5 | """Object that handles combinations of .only() and .exclude() calls""" |
| 6 | |
| 7 | ONLY = 1 |
| 8 | EXCLUDE = 0 |
| 9 | |
| 10 | def __init__( |
| 11 | self, fields=None, value=ONLY, always_include=None, _only_called=False |
| 12 | ): |
| 13 | """The QueryFieldList builder |
| 14 | |
| 15 | :param fields: A list of fields used in `.only()` or `.exclude()` |
| 16 | :param value: How to handle the fields; either `ONLY` or `EXCLUDE` |
| 17 | :param always_include: Any fields to always_include eg `_cls` |
| 18 | :param _only_called: Has `.only()` been called? If so its a set of fields |
| 19 | otherwise it performs a union. |
| 20 | """ |
| 21 | self.value = value |
| 22 | self.fields = set(fields or []) |
| 23 | self.always_include = set(always_include or []) |
| 24 | self._id = None |
| 25 | self._only_called = _only_called |
| 26 | self.slice = {} |
| 27 | |
| 28 | def __add__(self, f): |
| 29 | if isinstance(f.value, dict): |
| 30 | for field in f.fields: |
| 31 | self.slice[field] = f.value |
| 32 | if not self.fields: |
| 33 | self.fields = f.fields |
| 34 | elif not self.fields: |
| 35 | self.fields = f.fields |
| 36 | self.value = f.value |
| 37 | self.slice = {} |
| 38 | elif self.value is self.ONLY and f.value is self.ONLY: |
| 39 | self._clean_slice() |
| 40 | if self._only_called: |
| 41 | self.fields = self.fields.union(f.fields) |
| 42 | else: |
| 43 | self.fields = f.fields |
| 44 | elif self.value is self.EXCLUDE and f.value is self.EXCLUDE: |
| 45 | self.fields = self.fields.union(f.fields) |
| 46 | self._clean_slice() |
| 47 | elif self.value is self.ONLY and f.value is self.EXCLUDE: |
| 48 | self.fields -= f.fields |
| 49 | self._clean_slice() |
| 50 | elif self.value is self.EXCLUDE and f.value is self.ONLY: |
| 51 | self.value = self.ONLY |
| 52 | self.fields = f.fields - self.fields |
| 53 | self._clean_slice() |
| 54 | |
| 55 | if "_id" in f.fields: |
| 56 | self._id = f.value |
| 57 | |
| 58 | if self.always_include: |
| 59 | if self.value is self.ONLY and self.fields: |
| 60 | if sorted(self.slice.keys()) != sorted(self.fields): |
| 61 | self.fields = self.fields.union(self.always_include) |
no outgoing calls