A ListField that sorts the contents of its list before writing to the database in order to ensure that a sorted list is always retrieved. .. warning:: There is a potential race condition when handling lists. If you set / save the whole list then other processes trying t
| 987 | |
| 988 | |
| 989 | class SortedListField(ListField): |
| 990 | """A ListField that sorts the contents of its list before writing to |
| 991 | the database in order to ensure that a sorted list is always |
| 992 | retrieved. |
| 993 | |
| 994 | .. warning:: |
| 995 | There is a potential race condition when handling lists. If you set / |
| 996 | save the whole list then other processes trying to save the whole list |
| 997 | as well could overwrite changes. The safest way to append to a list is |
| 998 | to perform a push operation. |
| 999 | """ |
| 1000 | |
| 1001 | def __init__(self, field, **kwargs): |
| 1002 | self._ordering = kwargs.pop("ordering", None) |
| 1003 | self._order_reverse = kwargs.pop("reverse", False) |
| 1004 | super().__init__(field, **kwargs) |
| 1005 | |
| 1006 | def to_mongo(self, value, use_db_field=True, fields=None): |
| 1007 | value = super().to_mongo(value, use_db_field, fields) |
| 1008 | if self._ordering is not None: |
| 1009 | return sorted( |
| 1010 | value, key=itemgetter(self._ordering), reverse=self._order_reverse |
| 1011 | ) |
| 1012 | return sorted(value, reverse=self._order_reverse) |
| 1013 | |
| 1014 | |
| 1015 | def key_not_string(d): |