检查值存在于另一个表中

时间:2018-01-16 12:11:29

标签: python django

抱歉,我是学生。我有这个场景

class
Sorted

表格(设备 - 警报)没有任何关系:

  1. 我需要检查“警报”表中是否存在“设备”表的ID
  2. 如果需要返回A,如果没有返回B,则返回模板

1 个答案:

答案 0 :(得分:0)

有点难以分辨你想做什么,但你可以做一个

的组合
# will give all equipment_ids in all alerts
alerted_equipment_ids = Alert.objects.values_list('equipment_id', flat=True).distinct()

# will filter Equipment and give those with alerts
alerted_equipment = Equipment.objects.filter(pk__in=alerted_equipment_ids)

# will get alerts that has a valid equipment-ID
alerts_for_alerted_equipment = Alert.objects.filter(equipment_id__in=alerted_equipment.values_list('pk', flat=True))