0

假设我的项目中有一个评论模型:

class Comment(models.Model):
    text = models.TextField(max_length=500, blank=False)
    author = models.ForeignKey(User)

django.core.serializers当使用作者字段序列化为 JSON时,结果如下:

"author": 1 // use_natural_keys = False
"author": ["someuser"] // use_natural_keys = True

假设我也想输出用户的名字和姓氏?我该怎么做呢?

4

1 回答 1

1

我假设您正在序列化您的模型以便在线传输它(如在 http 响应中)。

django.core.serializers可能不是您想要的方式。一种快速的方法是在模型上包含一个方法来返回要序列化的字典,然后使用simplejson.dumps它来序列化它。例如:

def to_json(self):
    return dict(
        author=[self.author.natural_key(), self.author.first_name, self.author.last_name],
        text=self.text,
    )

然后打电话simplejson.dumps(comment.to_json())

于 2012-05-27T11:27:59.280 回答