我有两个模型(参与者,持有人)具有相同的字段:first_name
,last_name
和date_of_birth
在我的参与者模型的详细视图中,我检查这些字段是否与我的持有人模型中的字段相同:
for holder in Holder.objects.all():
if participant.last_name == holder.last_name and participant.first_name == holder.first_name and participant.date_of_birth == holder.date_of_birth:
has_item = True
,然后返回render_to_response
return self.render_to_response({
'has_item': has_item,
})
在我的HTML中,我得到了这个:
<td>{% if has_item %}<a href="{% url 'vouchers:holders' %}">Voucher(s) found</a> {% else %}No voucher found{% endif %}</td>
这会将用户从我的参与者的详细信息视图链接到我的凭单ListView,其中表中列出了所有Holder。现在我的问题是,当将用户重定向到此列表时,是否可以以某种方式突出显示找到具有凭证的确切用户?
例如,如果John Doe
有凭证,则在他的个人资料中显示链接,这会将他重定向到所有持有者的列表,并突出显示其FirstName
,Lastname
和Date of birth
相同。
是否可以使用JavaScript?
答案 0 :(得分:2)
无论您做什么,都不应遍历所有对象来查找匹配项。至少要求数据库执行此操作:
try:
matching_holder = Holder.objects.get(first_name=participant.first_name, last_name=participant.last_name, date_of_birth=participant.date_of_birth)
except Holder.DoesNotExist:
matching_holder = None
现在您可以在模板中使用matching_holder
。
但是正如我所说,您根本不应该这样做,您应该使用外键或其他关系字段。