如何通过 'custom' 字段查询用户模型? (django.db.models.fields.related_descriptors.ReverseOneToOneDescriptor)
How to query User model by 'custom' fields? (django.db.models.fields.related_descriptors.ReverseOneToOneDescriptor)
我使用 account
应用扩展了用户模型。
模型帐户应用程序:
from django.db import models
from django.contrib.auth.models import User
from departments.models import Department
class Account(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
profile_pic = models.ImageField(upload_to='profile_pics', blank=True)
department = models.ForeignKey(
Department, on_delete=models.SET_NULL, null=True, related_name='department')
def __str__(self):
return self.user.username
现在我需要将同一部门的用户计数发送到我的模板...
查看:
from django.contrib.auth.models import User
@login_required
def home(request):
context = {
'title': 'Dashboard',
'department_members': 'department_members': User.objects.filter(department=request.user.account.department).count(),
}
return render(request, 'app/dashboard.html', context)\
department_members 始终为 1,即使我在同一部门有更多用户。
我认为问题是 User
默认情况下没有 department
字段,所以我不能说 User.account.objects.filter(department=request.user.account.department)
我已经尝试了很多查询并查看了 django
文档,但我找不到关于如何检索此信息的正确方式。
有人遇到同样的问题吗?关于如何以更好的方式 debug/create 我的查询的任何提示?
提前致谢!
也许将 department_members
查询集更改为:
context = {
'title': 'Dashboard',
'department_members': Account.objects.filter(department=request.user.account.department).count() if hasattr(request.user, "account") else 0,
}
解决了您的问题。
我使用 account
应用扩展了用户模型。
模型帐户应用程序:
from django.db import models
from django.contrib.auth.models import User
from departments.models import Department
class Account(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
profile_pic = models.ImageField(upload_to='profile_pics', blank=True)
department = models.ForeignKey(
Department, on_delete=models.SET_NULL, null=True, related_name='department')
def __str__(self):
return self.user.username
现在我需要将同一部门的用户计数发送到我的模板...
查看:
from django.contrib.auth.models import User
@login_required
def home(request):
context = {
'title': 'Dashboard',
'department_members': 'department_members': User.objects.filter(department=request.user.account.department).count(),
}
return render(request, 'app/dashboard.html', context)\
department_members 始终为 1,即使我在同一部门有更多用户。
我认为问题是 User
默认情况下没有 department
字段,所以我不能说 User.account.objects.filter(department=request.user.account.department)
我已经尝试了很多查询并查看了 django
文档,但我找不到关于如何检索此信息的正确方式。
有人遇到同样的问题吗?关于如何以更好的方式 debug/create 我的查询的任何提示?
提前致谢!
也许将 department_members
查询集更改为:
context = {
'title': 'Dashboard',
'department_members': Account.objects.filter(department=request.user.account.department).count() if hasattr(request.user, "account") else 0,
}
解决了您的问题。