I’d like to store a dictionary as a string on my django model.
It would simply be a few key=value pairs separated by commas. I prefer not to pickle this so that it can easily be edited as a string.
I will use this field for arbitrary types of gateway arguments. For example, for the “Gift Card” payment gateway, i’d store a card_id code in this field.
For the CreditCard gateway, I’d store a transaction ID number.
Here’s what I came up with: please, comments and suggestions are welcome.
@property
def gateway_arguments(self):
"""
Dictionary stored as string.
"""
if not hasattr(self, '_gateway_arguments'):
try:
self._gateway_arguments = dict(
(x.strip().split('=') for x in self.gateway_args.split(',') if x)
)
except Exception, e:
log.critical("Malformed gatway_args on order {id}".format(id=self.id))
self._gateway_arguments = {}
return self._gateway_arguments
@gateway_arguments.setter
def gateway_arguments(self, value):
self._gateway_arguments = value
def save(self, *args, **kwargs):
""" Convert dictionary to string """
if getattr(self, '_gateway_arguments', None):
self.gateway_args = ','.join(('{key}={value}'.format(key=key, value=value) for
key, value in self._gateway_arguments.iteritems() ))
super(Order, self).save(*args, **kwargs)
how it works? i wanna make key-value store for all tables on django, but cannot find right solution and information how to use pickle.
Look up python pickle — pickled_data_string = pickle.dumps(my_python_object)
python_object_from_pickle = pickle.loads(pickled_data_string)