简体   繁体   English

django-用户的自然键序列化

[英]django - Natural key serialization of User

Suppose I have a model of a comment in my project: 假设我在项目中有一个注释模型:

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

When serialized to JSON using django.core.serializers the author field comes out as: 当使用django.core.serializers序列化为JSON时,author字段显示为:

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

Suppose I want to output the user's first and last name as well? 假设我也要输出用户的名字和姓氏? How would I go about that? 我将如何处理?

I assume you're serializing your model in order to transmit it on wire (like in a http response). 我假设您要对模型进行序列化,以便在线传输模型(例如在http响应中)。

django.core.serializers is likely not the way you want to go. django.core.serializers可能不是您想要的方式。 A quick approach would be to include a method on the model to return the dictionary you want to be serialized, then use simplejson.dumps to serialize it. 一种快速的方法是在模型上包括一个方法,以返回要序列化的字典,然后使用simplejson.dumps进行序列化。 Eg: 例如:

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

then just call simplejson.dumps(comment.to_json()) . 然后只需调用simplejson.dumps(comment.to_json())

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

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