我想在JSON响应中获取我的country_name字段中的所有值。
这是我的models.py:
from django.db import models
class Countries(models.Model):
country_name = models.CharField(max_length=100)
def __str__(self):
return str(self.country_name)
这是获得它的视图:
from django.http import Http404
from django.shortcuts import HttpResponse
from .models import Countries
import json
from django.core import serializers
def AllCountries(request):
countries = list(Countries.objects.all())
data = serializers.serialize('json', countries)
return HttpResponse(data, mimetype="application/json")
这是我得到的JSON响应:
[{“ pk”:1587,“ model”:“ interApp.countries”,“ fields”:{“ country_name”:“孟加拉国”}}}]
但是我不想要“ pk”和“ model”,我只想要所有的国家名称。
您可以改为使用QuerySet.values_list()
method获取所有国家/地区名称,然后以json编码形式发送此数据。
def AllCountries(request):
country_names = list(Countries.objects.values_list('country_name', flat=True))
data = {'country_names': country_names}
return HttpResponse(json.dumps(data), content_type="application/json")
您也可以使用JsonResponse
代替HttpResponse
。json.dumps()
然后将不需要这样做,因为这将由JsonResponse
类本身执行。
def AllCountries(request):
country_names = list(Countries.objects.values_list('country_name', flat=True))
data = {'country_names': country_names}
return JsonResponse(data)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句