mikec
mikec

Reputation: 3673

Storing a python set in a database with django

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 serialize 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.

Upvotes: 8

Views: 1445

Answers (4)

Ben Hughes
Ben Hughes

Reputation: 2547

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.

Upvotes: 1

Herman Schaaf
Herman Schaaf

Reputation: 48445

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.

Upvotes: 2

Ski
Ski

Reputation: 14487

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.

Upvotes: 0

nmichaels
nmichaels

Reputation: 50981

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.

Upvotes: 4

Related Questions