简体   繁体   中英

Django: to pass data JSON from view to javascript

I have my model

class Calendar(models.Model):
name = models.CharField(_('name'), max_length=50)



class Event(models.Model):
....
calendar = models.ForeignKey(Calendar, verbose_name=_('categorie'))

and my view:

event_list = []
events = Event.objects.all()

for event in events:
    event_list.append({
            'categorie': event.calendar
            })

return http.HttpResponse(json.dumps(event_list),
                             content_type='application/json')

I try to return event.categorie in a javascript file but It's not working alert(event.categorie) display undefined....

if I print event_list, I have

{'categorie': <Calendar: thermique>}

The problem comes from models.ForeignKey ?

You can't dumps Calendar instance to json. You should get error TypeError <Calendar: thermique> is not JSON serializable .

You need convert Calendar instance to dict of simple types. For example add method as_dict to Calendar:

class Calendar(models.Model):
    name = models.CharField(_('name'), max_length=50)

    def as_dict(self):
        return {
            'id': self.id,
            'name': self.name,
        }

and use it in you code:

for event in events:
    event_list.append({
        'categorie': event.calendar.as_dict(),
    })

it just the calendar names

Since all you need is the calendar names you can modify your query a little bit to use values but the real problem is probably called by needing to resolve the queryset

events = Event.objects.values('calendar__name')
return http.JsonResponse(status=200, 
                         {'categories': json.dumps(list(events))})

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