当我使用group by和join时,如何访问对象user
(来自Django管理)?
那我的查询:
Idea.objects.values("author_id").annotate(
total=Count('author_id'))
运行此查询,我得到以下结果:
<QuerySet [{'author_id': 1, 'total': 6}, {'author_id': 2, 'total': 8}]>
但是,我无法从User
(django admin的默认User
模型)访问值。在这种情况下,我只能在模板上访问author_id
和total
:
{% for d in ideas %}
{{d.total}} - {{d.author_id}}
{% endfor %}
我不能做这样的事情:d.author.user.email
我的模特:
class UserProfile(models.Model):
user = models.OneToOneField('auth.User', on_delete=models.PROTECT)
use_term_accept = models.NullBooleanField(default=False)
manager = models.NullBooleanField(default=False)
def __str__(self):
return self.user.username
class Idea(models.Model):
title = models.CharField(max_length=200)
creation_date = models.DateTimeField('data criação')
author = models.ForeignKey('users.UserProfile', on_delete=models.CASCADE, related_name='old_author')
authors = models.ManyToManyField('users.UserProfile', related_name='authors')
deleted = models.BooleanField(default=False)
答案 0 :(得分:1)
您可以通过向author__user__email
方法中添加author__user__email
来向结果中添加values
键。
示例:
Idea.objects.values("author_id", "author__user__email").annotate(
total=Count('author_id'))