Django Querysets - 添加字符串文字注释
我想从字面上将一个字符串添加到查询集对象中。为什么,因为我将其发送到 JSON,只需将信息放在那里并使其可用,而不必迭代查询集以将其转换为自定义字典,那就太好了,干净了。
我现在拥有的:
a_vote_set.aggregate(
count = Count('id'),
avg=Avg('score'),
std=StdDev('score'),
sum=Sum('score'),
)
这让我得到了这个:
{"count": 1, "std": 0.0, "sum": -4.0, "avg": -4.0}
我想要得到的是:
{"count": 1, "std": 0.0, "sum": -4.0, "avg": -4.0, "additional_value": "name of candidate"}
我希望通过调用这样的东西来得到:
a_vote_set.aggregate(
count = Count('id'),
avg=Avg('score'),
std=StdDev('score'),
sum=Sum('score'),
additional_value=Literal(candidate.name),
)
or this:
a_vote_set.aggregate(
count = Count('id'),
avg=Avg('score'),
std=StdDev('score'),
sum=Sum('score')
).append(
additional_value=str(candidate.name),
)
关于这是否可能的任何想法?
I want to literally add a string to a queryset object. Why, because I'm sending this to JSON and it would be so nice and clean to just put the information there and have it available without having to iterate over the queryset to turn it into a custom dictionary.
What I have now:
a_vote_set.aggregate(
count = Count('id'),
avg=Avg('score'),
std=StdDev('score'),
sum=Sum('score'),
)
Which gets me this:
{"count": 1, "std": 0.0, "sum": -4.0, "avg": -4.0}
What I want to get is:
{"count": 1, "std": 0.0, "sum": -4.0, "avg": -4.0, "additional_value": "name of candidate"}
Which I would love to get by calling something like this:
a_vote_set.aggregate(
count = Count('id'),
avg=Avg('score'),
std=StdDev('score'),
sum=Sum('score'),
additional_value=Literal(candidate.name),
)
or this:
a_vote_set.aggregate(
count = Count('id'),
avg=Avg('score'),
std=StdDev('score'),
sum=Sum('score')
).append(
additional_value=str(candidate.name),
)
Any ideas on if this is possible?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您也许可以使用 .extra () 之类的东西:
您也许还可以将 Q() 和 F() 值传递到选择中,但我不确定。
You might be able to use .extra() something like:
You may also be able to pass Q() and F() values into the select, but I'm not sure.
您可以使用 Value 添加文字值:
You can add literal value with Value: