只在JSON中返回一个字段

2024-09-30 10:29:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我只想返回clandpin字段。我有这个模型如下:

在模型.py在

class ButuanMaps(gismodel.Model):
class Meta:
    verbose_name = u'Butuan Map'
    verbose_name_plural = u'Butuan Maps'

clandpin = gismodel.CharField("Land PIN", max_length=50, null=True, blank=True)
ssectionid = gismodel.ForeignKey(Section)
#ssectionid_id = gismodel.IntegerField()
geom = gismodel.MultiPolygonField("Geom ID", srid=32651, null=True, blank=True)
objects = gismodel.GeoManager()

def __unicode__(self):
    return self.clandpin

在我的模板中,以下是AJAX的代码:

^{pr2}$

在视图.py公司名称:

    def section_landpins(request):
if request.method == "GET":
    m = ButuanMaps.objects.filter(ssectionid=request.GET['sectionid'])
    landpins = serializers.serialize("json", m.values('clandpin'), fields=("clandpin"))
    data = json.dumps({
        'pins': landpins,
    })
    return HttpResponse(data, content_type='application/json')

它返回了一个错误

 AttributeError at /sectionpins'dict' object has no attribute '_meta'

当我用以下命令更改查询时:

 m = ButuanMaps.objects.filter(ssectionid=request.GET['sectionid'])

它不会返回错误,但是:

{"pins": "[{\"pk\": 185625, \"model\": \"tbl.butuanmaps\", \"fields\": {\"clandpin\": \"162-12-0001-055-37\"}}

Tags: namepy模型jsontrueverbosegetobjects
1条回答
网友
1楼 · 发布于 2024-09-30 10:29:07

您可以通过从ORM中只请求您感兴趣的字段来完成此操作,然后将ValueQuerySet计算到字典列表中:

section_id = request.GET.get('sectionid', 'defaultid')

m = ButuanMaps.objects.filter(ssectionid=section_id).values('landpins')
return HttpResponse(json.dumps({'pins': list(m)}),
                               content_type='application/json')

相关问题 更多 >

    热门问题