简体   繁体   English

在Django中将字段序列化为JSON对象

[英]Serialize a field as a JSON object in Django

(Django 1.8.5) (Django 1.8.5)
Suppose I want to print out the number of answers and distinct questions for each user. 假设我想为每个用户打印出答案和不同问题的数量。


models.py: models.py:

class User(models.Model):
    id = models.AutoField(db_column='Id', primary_key=True)
    nickname = models.CharField(db_column='Nickname', db_index=True, max_length=255)
    email = models.EmailField(db_column='Email', db_index=True, null=True)


class Question(models.Model):
    id = models.AutoField(db_column='Id', primary_key=True)
    user = models.ForeignKey(User, on_delete=models.CASCADE, db_column='UserId')

class Answer(models.Model):
    id = models.AutoField(db_column='Id', primary_key=True)
    question = models.ForeignKey(Question, on_delete=models.CASCADE, db_column='QuestionId')
    user = models.ForeignKey(User, on_delete=models.CASCADE, db_column='UserId')

views.py: views.py:

from django.db.models import Count
stats = Answer.objects.values('user').annotate(number_of_answers=Count('id'), number_of_answered_questions=Count('question', distinct=True))

Now, 现在,

print(stats[0])

gives me 给我

{'number_of_answered_questions': 4, 'number_of_answers': 5, 'user': 1}

However, I would like the output to look like this: 但是,我希望输出看起来像这样:

{'number_of_answered_questions': 4, 'number_of_answers': 5, 'user': {'id':1, 'nickname': 'my_nickname'}}

What should my serializer(eg UserStatSerializer) be? 我的序列化器(例如UserStatSerializer)应该是什么?

Notes: 笔记:
1) I will not use the serializer for deserialization. 1)我不会使用序列化器进行反序列化。
2) I only want to know id & nickname. 2)我只想知道ID和昵称。 Other fields such as email(actually, there are other fields as well) should not be included in the result. 其他字段(例如电子邮件)(实际上也有其他字段)不应包含在结果中。

In fact this is the default values behaviour. 实际上,这是默认values行为。 If you have a field called user that is a ForeignKey , the default values() call will return a dictionary key called user_id, since this is the name of the hidden model attribute that stores the actual value. 如果您有一个名为user的字段,为ForeignKey ,则默认values()调用将返回一个名为user_id的字典键,因为这是存储实际值的隐藏模型属性的名称。 When you are calling values() and passing in field names, you can pass in either user or user_id and you will get back the same thing and the dictionary key will match the field name you passed in. 当您调用values()并传入字段名称时,您可以传入useruser_id ,然后返回相同的内容,并且字典键将与您传入的字段名称匹配。

You can do it manually: 您可以手动执行以下操作:

for stat in stats:
     stat['user'] = User.objects.filter(id=stat['user']).values('id', 'nickname')

Check Values() doc for more details. 查看Values()文档以获取更多详细信息。

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

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