简体   繁体   中英

Django: convert QuerySet with related objects to JSON

Let's suppose I have two simple Models:

class Place(models.Model):
    name = models.CharField(max_length=200)
    address = models.CharField(max_length=200)

class Event(models.Model):
    name = models.CharField(max_length=200)
    date = models.DateField()
    place = models.ForeignKey(Place)

What I want to do now is query a set of events with the resolved place, and convert everything to a list of dicts, that can be converted to JSON later on.

This is how the end result should look like:

[{
   "name": "event1",
   "date": "date1",
   "place": {
       "name": "place1",
       "address": "address1",
   },
},{
   "name": "event2",
   "date": "date2",
   "place": {
       "name": "place2",
       "address": "address2",
   },
},]

So far I tried my luck with ValueQuerySet and the .values() method:

Event.objects.all().select_related("place").values()

This however won't work, since .values() only returns the ids of related objects and not the content. So I was wondering if there is another built-in way to do this kind of conversion or if I have to iterate the QuerySet object and do the conversion by myself.

There is no default way to create the nested dicts you're after, but you can select the values of related items:

# No need for select_related in this case
Event.objects.values('name', 'date', 'place__name', 'place__address')

[{
   "name": "event1",
   "date": "date1",
   "place__name": "place1",
   "place__address": "address1",
},{
   "name": "event2",
   "date": "date2",
   "place__name": "place2",
   "place__address": "address2",
}]

If absolutely necessary, you can do some post-processing in Python to get the nested dicts you want.

There is a relevant method called model_to_dict :

from django.forms.models import model_to_dict
model_to_dict(instance, fields=[], exclude=[])

but it won't create dict fields from related models.

Here's the snippets you can use:

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