2016-03-19 43 views
1

我想在JSON響應中的country_name字段中獲取所有值。如何獲取django模型字段中的值?

這裏是我的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「:」bangladesh「}}]

但我不想要」pk「和「模型」,我只想要所有的國家名稱。

+1

https://docs.djangoproject.com/en/1.9/topics/serialization/#subset-of-fields –

回答

0

您可以改爲使用QuerySet.values_list()方法獲取所有國家名稱,然後以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) 
0

如果您想嘗試這不意味着序列化器遵循這一點,簡單的事情在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") 

只需使用2行以上更換你的3條線路,你可能加場的關係你從字典裏面的模型中想要什麼。

相關問題