Django文档不太清楚如何过滤对象,使它们包含相关字段的过滤子集。Django模型与相关字段的过滤子集
假设我有以下型号:
class Device(models.Model):
name = models.CharField(max_length=50)
class DeviceEvent(models.model):
device=models.ForeignKey(Device, null=False, related_name='device_events')
handled = models.BooleanField(default=Fasle)
现在假设我希望检索有未处理的DeviceEvents所有设备的列表。我如何在Django中编写查询来做到这一点?
最终结果应该是设备,其中devices是Device对象的列表,并且对于每个设备对象“device”,我们有device.device_events是未处理的DeviceEvent对象的列表。这可能在Django中做到吗?
或者,我可以做到这一点在Python这样的:
all_devices=Device.objects.all()
devices=[]
for thedevice in all_devices:
unhandled_device_events=thedevice.device_events.\
annotate(num_events=Count('device_events')).\
filter(device_event__device=thedevice).\
filter(num_events__gt=0).\
filter(device_event__handled=False).all()
if unhandled_device_events:
thedevice.device_events=unhandled_device_events
devices.append(thedevice)
在上面,我创建了一个名为设备的新列表,然后通过所有设备对象循环和手动添加设备到设备,只有当它至少有一个未处理的事件,并且该设备对象现在具有device.device_events =未处理的设备事件(不是所有设备事件)。这是允许的还是高效的?
或者当我将其中一个device_events称为“device_event”而不是“deviceevent”时,它是正确的?
没有,返回一个设备对象,而进去的语法看起来是错误的。 – Marc
你确定吗?你有没有测试过它?为什么里面的代码看起来错了? :) –