문제

Let's say I have an example like the doc's:

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',)

How would I do a JSON dump for a reporter, returning all the associated Articles? I was hoping something like this for the Reporter class:

    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(),
    }

but no such luck. I looked through the documentation, but everything seems to be geared towards the other direction.

도움이 되었습니까?

해결책

Try this :

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()]
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top