我正在尝试使用Jsonresponse返回一个对象,对不起,这是我的脚本:
setInterval(function()
{
$.ajax({
url: '/check_notification/',
type: "POST",
dataType: 'json',
success: function (data) {}
});
}, 2000);在我的django views.py中:
def check_notification(request):
user = request.user
profile = Person.objects.get(profile=user)
notification = NotificationRecipient.objects.filter(profile=profile)
return JsonResponse(model_to_dict(notification))发布于 2018-07-09 16:22:25
您可以为要作为响应传递的模型创建模型序列化程序。有关更多信息,请阅读django rest framework tutorial,了解如何进行json响应。或者,如果您有一个简单的字典,您可以在check_notification函数的末尾使用以下代码片段进行json响应。return HttpResponse(json.dumps(your dictionary))
发布于 2018-07-09 16:41:47
我建议你使用Django Rest Framework来返回JSON格式的响应,因为模型的序列化可以很容易地完成。您可以从here开始。在那里你会找到一种叫做ModelSerializer的东西。基本上,您可以在您的应用程序文件夹中创建一个包含以下内容的serializer.py:
from rest_framework import serializers
from .models import Person, NotificationRecipient
class PersonSerializers(serializers.ModelSerializer):
class Meta:
model = Person
fields = '__all__'
class NotificationRecipientSerializers(serializers.ModelSerializer):
class Meta:
model = NotificationRecipient
fields = '__all__'上面的代码将序列化您的模型,这意味着将被转换为json格式。在名为views_api.py的文件中,您可以创建一个将由URL使用调用的类,并定义您的查询集。在您的例子中,类将被定义为:
from rest_framework.views import APIView
from rest_framework.response import Response
from .models import Person, NotificationRecipient
from .serializers import NotificationRecipientSerializers
class NotificationAPIView(APIView):
def get(self,request):
user = request.user
profile = Person.objects.get(profile=user)
notification = NotificationRecipient.objects.filter(profile=profile)
return Response(notification)这将以JSON格式返回响应。在urls.py文件中,按如下方式调用NotificationAPIView:
从django.urls从.import views_api导入路径
urlpatterns = [
path('check/notification/', views_api.NotificationAPIView.as_view(), name='notification'),
]希望你对那里发生的事情有一个基本的了解。要更好地理解,请参阅Django Rest框架文档。
https://stackoverflow.com/questions/51240749
复制相似问题