在你的模型中Device and History模型与从 History 到 DeviceModel 的外键相关,这意味着当您有一个 History 对象时,您可以检索与其相关的设备模型,反之亦然(如果您有一个设备,您可以获取其历史记录)。
Example:
first_history = History.objects.all()[0]
first_history.device # This return the device object related with first_history
first_history.device.name # This return the name of the device related with first_history
但它也可以以另一种方式工作,你可以这样做:
first_device = Device.objects.all()[0]
first_device.history # This return the history object related with device
first_device.history.transition_date # Exactly as before, can access history fields
所以在你的查询中:
devices = DeviceModel.objects.filter(history__transition_date__range=(startDate, endDate))
这将返回一个设备列表,但您可以访问与每个设备对象相关的历史记录
这对你来说还不够吗?您有一个设备列表,每个设备都可以访问其相关的历史记录对象
Info:当你声明一个外键字段模型默认通过 id 相关,我这样说是因为你正在做:
device = models.ForeignKey(DeviceModel, to_field='id')
如你所见,你正在使用to_field='id'
但这种关系是默认完成的,如果你这样做:
device = models.ForeignKey(DeviceModel)
你会得到相同的结果
(EDIT)使用.values()获取列表[device.name,history.date]
得到一个像你说的清单[device.name, history.date]
您可以使用.values()
Django QuerySet的功能,官方文档here https://docs.djangoproject.com/en/dev/ref/models/querysets/#django.db.models.query.QuerySet.values
你可以尝试这样的事情:
devices = DeviceModel.objects.filter(history__transition_date__range=(startDate, endDate)).values('name','history__transition_date')
# Notice that it is 'history _ _ transition_date with 2 underscores