How to store HStore field properly?

509 views Asked by At

Here I have a HStoreField which will be taken from user Input.

User gives the input in the format s:Small,l:Large, But I think the HStoreField needs the data type like this{'s': 'Small','l':'Large'}.

How can I covert the user data into this format so that I can store into the HStoreField.

Or simply I need to store the data. How can I do it ?

class MyModel(models.Model):
      properties = HStoreField()

# view 
properties = request.POST.get('properties')
print(properties)

#properties has data in this format s:Small,l:Large,

MyModel.objects.create(properties=properties)

I get the error like this.

django.db.utils.InternalError: Unexpected end of string
LINE 1: ...antity_reserved") VALUES ('ttt', 11, 'ttt', '55', 'Small:rrr...
1

There are 1 answers

5
Fedor Soldatkin On BEST ANSWER

You can parse the properties string and create dictionary from it:

properties = 's:Small,l:Large,'

properties_dict = {}
for pair in properties[:-1].split(','):
    key, value = pair.split(':')
    properties_dict[key] = value

>>> print(properties_dict)
{'s': 'Small', 'l':'Large'}