[XXX]处的ManyRelatedManager对象不是JSON可序列化的

时间:2015-08-04 20:25:52

标签: python json django django-models getjson

我有一个简单的模型.directive('myDirective', function() { return { template: '<h1> Hello World</h1>' }; }); 我正在序列化为JSON:

models.py:

<my-directive></my-directive>

views.py:

ManyToManyFields

但是我得到以下TypeError:

class Meeting(models.Model):
    site = models.ForeignKey(Site)
    meeting_title = models.CharField(default='', max_length=128, blank=True, null=True)
    meeting_team_members = models.ManyToManyField(Team, blank=False, null=False) # hosts
    meeting_visitors = models.ManyToManyField(Visitor, blank=False, null=False) # invited guests

1 个答案:

答案 0 :(得分:3)

如果@Brobin建议由于某种原因没有帮助......

meeting_team_members = [x.as_dict() for x in ins.meeting_team_members.all()]

class Team(models.Model):
    # ... example fields
    def as_dict(self):
        context = {
            'pk': self.id,
            'name': self.name,
            'description': self.description,
        }

        if self.image:
            context['image'] = get_thumbnail(self.image, '150').url
            context['full_image'] = self.image.url
        else:
            context['no_image'] = _(u'No image)  # this is just for localization

        return context

修改

for ins in instances: #populate list
     context.append({
        'meeting_title': ins.meeting_title, 
        'meeting_team_members':[x.as_dict() for x in ins.meeting_team_members.all()]
     })