Python 如果外键字段包含登录用户,则从模型中筛选对象
views.pyPython 如果外键字段包含登录用户,则从模型中筛选对象,python,django,Python,Django,views.py from django.shortcuts import render from notifications.models import Notification from django.shortcuts import render,Http404,redirect,get_object_or_404 from django.db.models import Q def TrainerDashView(request): if not request.user.is_
from django.shortcuts import render
from notifications.models import Notification
from django.shortcuts import render,Http404,redirect,get_object_or_404
from django.db.models import Q
def TrainerDashView(request):
if not request.user.is_authenticated:
return redirect('accounts:index')
else:
print(request.user.username)
notifications = Notification.objects.filter(receiver__username__in
= request.user.username)
count=Notification.objects.filter(receiver__username__in =
request.user.username).count()
print("NOTIFYNIUM: ",count)
context={
'notifications':notifications,
}
return render(request,'trainer_dash.html',context)
我的模型通知包含一个名为receiver的字段,它是所有用户模型的外键。如果receiver字段包含当前登录的用户,我想选择通知中的所有对象。“我的代码”不返回任何对象,即使用户从管理员激活,过滤器
\uu in=x
会与iterablex
中的每个元素进行比较。在您的例子中,x
是一个字符串,因此您正在筛选收件人用户名实际上是request.user.username
中的字符之一的通知。只需删除中的\u即可:
notifications = Notification.objects.filter(receiver__username=request.user.username)
或者更好,直接对用户进行过滤:
notifications = Notification.objects.filter(receiver=request.user)
过滤器\uuu in=x
与iterablex
中的每个元素进行比较。在您的例子中,x
是一个字符串,因此您正在筛选收件人用户名实际上是request.user.username
中的字符之一的通知。只需删除
中的\u即可:
notifications = Notification.objects.filter(receiver__username=request.user.username)
或者更好,直接对用户进行过滤:
notifications = Notification.objects.filter(receiver=request.user)
还有一个更简短的版本,它使用了ForeignKey的相关名称。假设您没有更改默认设置:
notifications = request.user.notification_set.all()
还有一个更简短的版本,它使用了ForeignKey的相关名称。假设您没有更改默认设置:
notifications = request.user.notification_set.all()
我在这里过滤用户名而不是直接过滤外键的唯一情况是,如果用户名是非唯一的,我希望有时会得到倍数。坚持主键(在第二个示例中是隐式的)可以确保它是唯一的、非空的和索引的;在处理自定义用户模型的情况下(或者更一般地说,在任何其他关系中,当您期望单个结果时,您可以选择查询PK),这些事情中的一些或所有可能都不正确。在这里,我只会筛选用户名
,而不是直接在外键上筛选,如果用户名是非唯一的,我希望有时会得到倍数。坚持主键(在第二个示例中是隐式的)可以确保它是唯一的、非空的和索引的;在处理自定义用户模型的情况下(或者,更一般地说,在任何其他关系中,当您期望单个结果时,您可以选择查询PK),这些事情中的一些或所有可能都不正确。