Ray Tango Ray Tango - 1 year ago 81
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": "[
\"quantity\":\"pdv %1\"},

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

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


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='',
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 Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download