What I’m trying to do:
Keep the order of inserted items in a Simple Object column in the database
What I’ve tried and what’s not working:
Using OrderedDict from collections. This worked to add to the database, but when I go to call the value of that column up, it’s now of type dict rather than OrderedDict
Is there an Anvil specific way to make sure the order of my keys in my dictionary is in order or is there something else I need to do to maintain the OrderedDict type?
If you want to use OrderedDict Perhaps you can store the information in the DB explicitly as a list of tuples?
d = OrderedDict({‘blub’: 1, ‘blob’: 2}) → OrderedDict([(‘blub’, 1), (‘blob’, 2)])
l = list(d.items()) → [(‘blub’, 1), (‘blob’, 2)]
then fill the table with ‘l’
reverse:
d = OrderedDict(l)
OrderedDict([(‘blub’, 1), (‘blob’, 2)])
Hmm, I believe that would work. Thanks for the workaround suggestion @j.vanrenen!
On the feature side, are SimpleObject Columns supposed to be able to store Ordered Dicts (i.e. is this a bug)? Or is that something they were never intended to contain?
By default, serialization of ordered dicts between the client and server does not maintain the ordering. I’d suggest adding a field to your dict that indicates the order, and sorting by that field on the far end.
I don’t know the design decision, but considering that those objects come from postgres, go to python on the server, to another python interpreter on the client and are stored in javascript, I would not expect for any effort to be spent in keeping them ordered
The docs include the specs for simple objects here: Anvil Docs | Storing Data in Data Tables
Ordered dicts will be included as normal dictionaries in a simple object column.
I agree with this, and if there were some super specific reason why they did, then the one off reason would require a one-off solution, like storing a list of indexable “ordered” keys in a single tuple, along side your dictionary as a simple object, then unpacking both, iterating over the list and calling each key. (Like what you did when you were a noob and didn’t know what collections was, or used python < 3.5 )
(And by you I mean me )