Python 如何获取django模型字段中的值?
我想在JSON响应中获取我的国家/地区名称字段中的所有值 这是我的models.py:Python 如何获取django模型字段中的值?,python,json,django,Python,Json,Django,我想在JSON响应中获取我的国家/地区名称字段中的所有值 这是我的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 im
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,“模式”:“跨党国家”,“领域”:{“国家名称”:“孟加拉国”}]
但是我不想要“pk”和“model”,我只想要所有的国家/地区名称。如果你想在不使用序列化程序的情况下尝试此方法,请遵循此方法,这在views.py中很简单
data = map(lambda x:{'country_name':x.country_name},Countries.objects.all())
return HttpResponse(content=json.dumps({'data':data}),content_type="application/json")
只需将您的3行替换为以上2行,您就可以在字典中的模型中添加任何您想要的字段。如果您想在不使用序列化程序的情况下尝试此方法,请遵循此方法,这是在views.py中完成的简单操作
data = map(lambda x:{'country_name':x.country_name},Countries.objects.all())
return HttpResponse(content=json.dumps({'data':data}),content_type="application/json")
只需将3行替换为以上2行,您就可以在字典中的模型中添加任何您想要的字段。您可以改为使用方法获取所有国家的名称,然后以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")
您还可以使用而不是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)
您可以改为使用方法获取所有国家的名称,然后以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")
您还可以使用而不是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)