Ray Tango Ray Tango - 3 months ago 18
JSON Question

Django deserialization of JSON stored in a model field

I'm new to Django/Python and currently working on a project with a friend. His android app sends data to me in JSON format that looks like this:

"datum_isteka": "2",
"e_mail": "null",
"adress": "null",
"goods": "[
{\"price\":\"2\",
\"good\":\"dobro1\",
\"tax_value\":\"2\",
\"quantity\":\"pdv %1\"},

{\"price\":\"3\",
\"good\":\"dobro 2\",
\"tax_value\":\"3\",
\"quantity\":\"pdv %3\"}
]",
"taxes": 5,
"order_num": 477456,
"store_user": 2


In my models this is stored in one field (the
goods
) and in my view i get this whole
goods
part of this JSON represented like this up here... My question is how do i turn this JSON field
goods
to something that is readable to a user. I'm using DRF for communication with android app.

Model:

class Obraz(models.Model):
datum_isteka = models.CharField(max_length=100,blank=True,
default='', null=True)
e_mail = models.CharField(max_length=100, blank=True,
default='', null=True)
adress = models.CharField(max_length=100, blank=True, null=True)
taxes = models.CharField(max_length=100)
order_num = models.CharField(max_length=100, blank=True, default='',
null=True)
goods = models.CharField(max_length=10000)
store_user=models.ForeignKey(Owner, default='Owner')


Model serializer:

class ObrazSerializer(serializers.ModelSerializer):
class Meta:
model = Obraz
fields = ('datum_isteka', 'e_mail', 'adress', 'taxes',
'order_num','goods ', 'store_user',)

Answer

I'd use a JSONField on the model

class Obraz(models.Model):
    ...
    goods = jsonfield.JSONField()

and a JSONField (notice it's not the same field) on the serializer:

class ObrazSerializer(serializers.ModelSerializer):
    goods = serializers.JSONField()
    class Meta:
        model = Obraz
        fields = ('datum_isteka', 'e_mail', 'adress', 'taxes', 
                  'order_num','goods', 'store_user',)

hope this helps

Comments