我正在尝试以以下格式从服务器接收帖子:
{
"event_type": "test",
"event_info": {
"key": "value",
"more unknown key":"Value pairs"...
}
}
然后将其序列化为sqlite db。
我找不到一个很好的方法来做到这一点。它不喜欢{}我得到返回“不是有效的字符串。”我还没有找到一个接受json对象的好方法。我可以将json存储为字符串,但我无法弄清楚如何将它转换为字符串。
我有views.py:
from django.shortcuts import render
from .models import Subscription
from .Serializers import SubscriptionSerializer
from rest_framework import viewsets
from django.http import HttpResponse
class SubscriptionViewSet(viewsets.ModelViewSet):
queryset = Subscription.objects.all().order_by('-date_created')
serializer_class = SubscriptionSerializer
http_method_names = ['get', 'post', 'delete']
models.py
from __future__ import unicode_literals
from django.db import models
class Subscription(models.Model):
event_type = models.TextField(default='Failed to set')
event_info = models.TextField(default='Failed to set')
date_created = models.DateTimeField(auto_now=True)
Serializers.py
from rest_framework import serializers
from .models import Subscription
class SubscriptionSerializer(serializers.ModelSerializer):
class Meta:
model = Subscription
fields = ('id', 'event_type', 'event_info')
答案 0 :(得分:0)
尝试使用嵌套的序列化程序:
class KeySerializer(serializers.Serializer):
key = serializers.CharField(max_length=30)
class EventSerializer(serializers.Serializer):
event_type = serializers.CharField(max_length=30)
event_info = KeySerializer()
EventSerializer应该能够解析/验证您发布的json。