开发者

Storing a python set in a database with django

开发者 https://www.devze.com 2023-02-13 02:09 出处:网络
I have a need to store a python set in a database for accessing later.What\'s the best way to go about doing this?My initial plan was to use a textfield on my model and just store the set as a comma o

I have a need to store a python set in a database for accessing later. What's the best way to go about doing this? My initial plan was to use a textfield on my model and just store the set as a comma or pipe delimited string, then when I need to pull it back out for use in my app I could initialize a set by calling split on the string. Obviously if there is a simple way to serializ开发者_运维知识库e the set to store it in the db so I can pull it back out as a set when I need to use it later that would be best.


If your database is better at storing blobs of binary data, you can pickle your set. Actually, pickle stores data as text by default, so it might be better than the delimited string approach anyway. Just pickle.dumps(your_set) and unpickled = pickle.loads(database_string) later.


There are a number of options here, depending on what kind of data you wish to store in the set.

If it's regular integers, CommaSeparatedIntegerField might work fine, although it often feels like a clumsy storage method to me.

If it's other kinds of Python objects, you can try pickling it before saving it to the database, and unpickling it when you load it again. That seems like a good approach.

If you want something human-readable in your database though, you could even JSON-encode it into a TextField, as long as the data you're storing doesn't include Python objects.


Redis natively stores sets (as well as other data structures (lists, dicts, queue)) and provides set operations - and its rocket fast too. I find it's the swiss army knife for python development.

I know its not a relational database per se, but it does solve this problem very concisely.


What about CommaSeparatedIntegerField?

If you need other type (string for example) you can create your own field which would work like CommaSeparatedIntegerField but will use strings (without commas).

Or, if you need other type, probably a better way of doing it: have a dictionary which maps integers to your values.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号