gpt4 book ai didi

python - Django 查询功能无法正确过滤用户类型

转载 作者:行者123 更新时间:2023-12-01 01:12:17 27 4
gpt4 key购买 nike

我正在尝试过滤所有用户,并选择具有 user is Teacher = Trueuser has Instrument1 ='Cello' 的用户。我的功能是显示所有用户,而不仅仅是教师,其中 user has Instrument1 ='Cello'。我想知道如何正确编写我的函数,以便它也选择老师。如果用户是教师,他们将使用 user.teacher=1 保存在我的数据库中,否则 user.teacher=0

View .py

def teacher_list(request):
data = User.objects.filter(Q(teacher=True) and Q(instrument1='Cello'))
form = TeacherProfileForm()
context = {'form' : form, 'data' : data}
return render(request, 'view/teacher_list.html', context)

HTML

<div class="desktop">
{% for user in data %}
<div class="row">
<div class="col-md-4 left">
<img src="{{ user.avatar.url }}" height="170" width="170">
</div>

<div class="col-md-4 mid">
<h3>{{ user.first_name|capfirst }} {{ user.last_name|capfirst }}</h3>
<h5>{% if user.instrument1 != "" %}{{ user.instrument1|capfirst }}{% endif %}{% if user.instrument2 != ""%}, {{ user.instrument2|capfirst }}{% endif %}{% if user.instrument3 != "" %}, {{user.instrument3|capfirst }}{% endif %}{% if user.instrument4 != "" %}, {{ user.instrument4|capfirst}}{% endif %}{% if user.instrument5 != "" %}, {{ user.instrument5|capfirst }}{% endif %}</h5>
<p>{{ user.bio|capfirst }}</p>
</div>

<div class="col-md-4 right">
<br />
<x-star-rating value="5" number="5" id="rating"></x-star-rating>
<br />
<br />
<br />
<a href="{% url 'view:profile' user.id %}">
<button type="submit" name="submit" class="btn blue_button">Book Lesson</button>
</a>
</div>

</div>
<hr />
{% endfor %}

最佳答案

简而言之:不要使用and运算符来组合Q对象。在 Python 中,and 运算符返回其中一个操作数,具体取决于第一个操作数的真实性。使用 &,或者像这里一样,您可以简化表达式。

背景:不要使用来组合两个Q对象。 Python 中的 and 是一个检查第一个操作数的真实性的函数,如果该操作数为 False,则返回第一个操作数,否则返回第二个操作数。这意味着:

>>> Q(teacher=True) and Q(instrument1='Cello')
<Q: (AND: ('instrument1', 'Cello'))>

而:

>>> Q(teacher=True) & Q(instrument1='Cello')
<Q: (AND: ('teacher', True), ('instrument1', 'Cello'))>

确实,由于具有条件的 Q 对象具有真值 True,因此 Q(teacher=True) 和 Q(instrument1='Cello') code> 表达式将返回第二个操作数,因此 Q(instrument1='Cello')

事实上,您首先不需要 Q 对象,您可以像这样查询:

def teacher_list(request):
data = User.objects.filter(<b>teacher=True, instrument1='Cello'</b>)
form = TeacherProfileForm()
context = {'form' : form, 'data' : data}
return render(request, 'view/teacher_list.html', context)

关于python - Django 查询功能无法正确过滤用户类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54736087/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com