简体   繁体   English

Django:将数据JSON从视图传递到javascript

[英]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.... 我尝试在JavaScript文件中返回event.categorie,但是它无法正常运行Alert(event.categorie)显示未定义。...

if I print event_list, I have 如果我打印event_list,我有

{'categorie': <Calendar: thermique>}

The problem comes from models.ForeignKey ? 问题来自models.ForeignKey?

You can't dumps Calendar instance to json. 您不能将Calendar实例转储到json。 You should get error TypeError <Calendar: thermique> is not JSON serializable . 您应该得到错误TypeError <Calendar: thermique> is not JSON serializable

You need convert Calendar instance to dict of simple types. 您需要将Calendar实例转换为简单类型的dict。 For example add method as_dict to Calendar: 例如,将方法as_dict添加到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 由于您只需要日历名称,因此您可以对查询进行一些修改以使用values但是真正的问题可能是通过解决查询集而引起的

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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