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.

    @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)
Advertisements

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.

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s