Django / Python — Store Dictionary as String


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.

    def gateway_arguments(self):
        Dictionary stored as string.
        if not hasattr(self, '_gateway_arguments'):
                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(
               self._gateway_arguments = {}
        return self._gateway_arguments

    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)

2 thoughts on “Django / Python — Store Dictionary as String

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

    1. Look up python pickle — pickled_data_string = pickle.dumps(my_python_object)
      python_object_from_pickle = pickle.loads(pickled_data_string)

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s