外键关系的JSON

时间:2013-07-14 21:09:15

标签: django json django-models django-related-manager

假设我有一个像doc这样的例子:

class Reporter(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)
    email = models.EmailField()

    def __unicode__(self):
        return u"%s %s" % (self.first_name, self.last_name)



class Article(models.Model):
    headline = models.CharField(max_length=100)
    pub_date = models.DateField()
    reporter = models.ForeignKey(Reporter)

    def __unicode__(self):
        return self.headline
    def json(self):
        return {
            'headline': self.headline,
            'pub_date': self.pub_date,
    }

    class Meta:
        ordering = ('headline',)

如何为记者执行JSON转储,返回所有相关文章?我希望Reporter课上有这样的东西:

    def json(self):
    return {
                'first_name': self.first_name,
                'last_name': self.last_name,
                'email': self.email,
                'articles': for a in self.article_set:
                                    a.json(),
    }

但没有这样的运气。 我查看了文档,但似乎所有内容都面向另一个方向。

1 个答案:

答案 0 :(得分:3)

试试这个:

def json(self):
return {
            'first_name': self.first_name,
            'last_name': self.last_name,
            'email': self.email,
            'articles': [ a.json for a in self.article_set.all()]
}