我想要独特的元素hubcode_list
。我可以这样做
hubcode_alarm_obj = HubAlarm.objects.all()
for obj in hubcode_alarm_obj:
hubcode = obj.hubcode
if hubcode not in hubcode_list:
hubcode_list.append(hubcode)
我想使用列表理解。我正在尝试这个,但它说hubcode_list
未定义,这是正确的错误。我怎样才能只添加独特的元素hubcode_list
hubcode_alarm_obj = HubAlarm.objects.all()
hubcode_list = [obj.hubcode for obj in hubcode_alarm_obj if obj.hubcode not in hubcode_list]
我也可以通过以下方式做到这一点:-
hubcode_list = list(set([obj.hubcode for obj in hubcode_alarm_obj]))
但设置又是另一个操作。我可以通过使用来做到这一点吗if-statement
在列表理解中?
由于您使用的是 django,因此让数据库为您进行过滤。这将是(迄今为止)最快的选择:
objects = HubAlarm.objects.exclude(hubcode__in=hubcode_list)
See the 文档 https://docs.djangoproject.com/en/dev/ref/models/querysets/#exclude了解更多。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)