[英]Django serializing Queryset with related entity fields
I'm trying to join 2 entities, get specific fields from them, and return a JSON of that. 我正在尝试加入2个实体,从它们中获取特定字段,然后返回该JSON。
I tried writing the following code: 我尝试编写以下代码:
import datetime
result = Foo.objects.all()
result = result.select_related('bar').extra(select={'bar_has_address':'IF(bar.has_address = '',0,1)'})
result = result.filter(time__gte=datetime.date.today())
return HttpResponse(serializers.serialize('json', result),mimetype="application/json")
Now I'm only getting a json containing the fields of Foo, whereas I want to get Bar's fields as well, ideally the returned JSON would have specific fields from both entities: 现在,我只得到一个包含Foo字段的json,而我也想获取Bar的字段,理想情况下,返回的JSON将具有来自两个实体的特定字段:
[{
'name': 'lorem ipsum', //from Foo
'has_address': 1, //from Bar
'address': 'some address', //from Bar
'id': 1, //from Foo
},... ]
even under result.values('...')
I'm not getting any of Bar's fields 即使在result.values('...')
我也没有得到Bar的任何字段
What am I missing here? 我在这里想念什么?
As far as I know, django built-in serializers cannot work with model related fields. 据我所知,django内置的序列化器无法与模型相关的字段一起使用。 Take a look at: 看一眼:
Also see: 另请参阅:
Hope that helps. 希望能有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.