【发布时间】:2021-12-19 10:50:51
【问题描述】:
我正在构建一个博客应用程序,我正在尝试获取Profile 模型的所有布尔值。我之前尝试过制作一个布尔值列表,但它不符合要求。
文件models.py
class Profile (models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, unique=True)
name = models.CharField(max_length=30)
first_boolean = models.BooleanField(default=False)
second_boolean = models.BooleanField(default=False)
third_boolean = models.BooleanField(default=False)
文件views.py
def page(request):
All_Booleans = Profile.objects.filter()
context = {'Booleans_List'}
return render(request, 'page.html', context)
我还尝试了from django.db.models import F 中的 F 之类的:
All_Booleans = Profile.objects.filter(F(first_boolean=request.user) | F(second_boolean=request.user))
但它正在显示:
init() 得到了一个意外的关键字参数“first_boolean”
我想做什么? -
我正在尝试获取 request.user 的 Profile Model 的所有布尔字段
但是我该怎么做呢?
【问题讨论】:
-
我仍然不清楚你的目标是什么。如果你排除了为真的布尔值,你会得到一个由零个、一个、两个或三个布尔值组成的列表,所有这些布尔值都是
False。但是我不清楚你想用那个列表做什么。此外,request.user.profile将不起作用,因为用户可以与您的建模中的许多Profiles 相关。 -
我会跟踪每个
Boolean,如果它不起作用,我怎样才能得到所有Booleans of a Model? -
@Van 请参阅What is the XY problem? 更不用说我们不知道这里的 X 是什么,我连这里的 Y 都无法理解。请在您的问题中添加更多详细信息,您到底想做什么?
-
@Van:我根本不明白你想做什么。取决于它可能会起作用。但是您可以简单地将
profile传递给模板,并在那里渲染布尔值。但我认为现在要解决的第一个问题是检索User的.profile。由于您使用的是ForeignKey,而不是OneToOneField,这意味着用户对象中没有添加.profile。
标签: python django django-models django-views django-queryset