Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to sort a List(Nested()) based on data not available in the dumped version? #2037

Closed
ThiefMaster opened this issue Aug 23, 2022 · 1 comment
Labels

Comments

@ThiefMaster
Copy link

I have a list of nested objects which have a property that can act as a sort key. However, that property is not part of the schema since it's not useful in the dumped version.

I'm looking for a way to sort the data using this property.

  • pre_dump won't work because i'd need to modify the actual object to be dumped - not a good idea in case of ORM model instances
  • post_dump won't work because i don't have the data
  • post_dump(pass_original=True) would be cumbersome because i'd have to get the order from the original ones but then apply it to the dumped data

The ideal option would be a way to intercept how the data for the List() gets loaded. That way I could simply return a sorted list without touching the original one. Is there already a way to do that? Something like @get_value('mylistattribute') to override how it gets loaded from the data-to-be-dumped? The only other alternative I see is subclassing List and add sorting support in there...

@ThiefMaster
Copy link
Author

FWIW this is what I ended up using, but if there's a better way please let me know:

class SortedList(fields.List):
    """
    Like the normal List, but when dumping a sort key can be specified.
    This allows sorting the data even without having the information needed
    for sorting in the final dumped data.
    """

    def __init__(self, *args, sort_key, **kwargs):
        self.sort_key = sort_key
        super().__init__(*args, **kwargs)

    def _serialize(self, value, attr, obj, **kwargs):
        if value is None:
            return None
        value = sorted(value, key=self.sort_key)
        return super()._serialize(value, attr, obj, **kwargs)

@sloria sloria closed this as completed Jan 5, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

3 participants