2014-04-04 31 views
0

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”时,它是正确的?

回答

0

如果我理解正确你的问题,我认为这应该工作

Device.objects.get(Device.device_events.handled = False) 
+0

没有,返回一个设备对象,而进去的语法看起来是错误的。 – Marc

+0

你确定吗?你有没有测试过它?为什么里面的代码看起来错了? :) –

0

因为它是一个ForeignKey关系,我相信你可以抓住时都兴奋到设备与此(假设d的DeviceEvents的是一个实例设备类的):

d.deviceevent_set.all() 

你应该能够过滤掉,像这样:

d.deviceevent_set.filter(handled=False) 

我没有测试过这个,但我认为它会工作。

编辑:在阅读您的评论后,我意识到我没有像我想象的那样仔细阅读您的问题。

在拔出所需设备后,您可以在for循环中使用上面的代码。获取设备实例,然后使用此代码段获取与该设备关联的未处理事件。例如,遍历device.objects.all()中的所有内容并检查d.device_set.filter(handled = false)是否为每个设备返回任何内容。如果是,则可以将该设备作为关键字添加到字典中,并将未处理的事件列表作为关联值添加到字典中。你将得到一个设备字典[unhandledevents]。如果你想的话,This post可以告诉你更多关于这个的信息。

您能否以您需要的方式操纵数据,或者我是否根据您的要求来操作数据?

+0

是的,但我想所有的设备不是所有的设备事件 – Marc

0

试试这个

d = Device.objects.filter(device_events__handled=False)