简体   繁体   中英

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.
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:

[{
    '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
What am I missing here?

As far as I know, django built-in serializers cannot work with model related fields. Take a look at:

Also see:

Hope that helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM