Django-连接两个模型
对于以下型号,我希望检索历史记录表中具有指定时间间隔之间转换日期的所有设备:Django-连接两个模型,django,django-models,Django,Django Models,对于以下型号,我希望检索历史记录表中具有指定时间间隔之间转换日期的所有设备: class History(models.Model): device = models.ForeignKey(DeviceModel, to_field='id') transition_date = models.DateTimeField() class Meta: db_table = 'History' class DeviceModel(models.Model)
class History(models.Model):
device = models.ForeignKey(DeviceModel, to_field='id')
transition_date = models.DateTimeField()
class Meta:
db_table = 'History'
class DeviceModel(models.Model):
id = models.IntegerField()
name = models.CharField()
class Meta:
db_table = 'Devices'
devices = DeviceModel.objects.filter(history__transition_date__range=(startDate, endDate))
我有一段代码,用于过滤指定的时间间隔:
class History(models.Model):
device = models.ForeignKey(DeviceModel, to_field='id')
transition_date = models.DateTimeField()
class Meta:
db_table = 'History'
class DeviceModel(models.Model):
id = models.IntegerField()
name = models.CharField()
class Meta:
db_table = 'Devices'
devices = DeviceModel.objects.filter(history__transition_date__range=(startDate, endDate))
这将为我提供与History
表中transition\u date
在指定范围内的行数相同的行数。
filter函数在设备id
上的设备模型
和历史
之间执行内部联接,仅检索设备模型
字段。我的问题是,如何同时从历史记录
和设备模型
中检索数据,同时将它们与设备id上的过滤器/选择单元连接起来。
我不想编写自定义SQL查询。在您的模型中设备和历史记录模型与从历史记录到设备模型的外键相关,这意味着当您有一个历史记录对象时,您可以检索与其相关的设备模型,反之亦然(如果您有一个设备,您可以获取其历史记录) 例如:
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))
这将返回设备列表,但您可以访问与每个设备对象相关的历史记录
这对你来说还不够吗?您有一个设备列表,每个设备都可以访问其相关的历史对象
信息:当您声明一个ForeignKey字段时,默认情况下模型是按id关联的,我这样说是因为您正在执行以下操作:
device = models.ForeignKey(DeviceModel, to_field='id')
正如您所看到的,您正在使用来_field='id'
,但是如果您执行以下操作,则默认情况下会完成此关系:
device = models.ForeignKey(DeviceModel)
你会得到同样的结果
(编辑)使用.values()获取列表[device.name,history.date] 要获得如您所说的列表,可以使用Django 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
我想序列化这些设备+每个设备的历史记录,并将它们作为HttpResponse返回,当我序列化它们时,我只获取设备。将您希望看到的历史记录字段添加到您正在执行的查询中。您可以使用django函数序列化查询,django查询的结果需要什么?你想如何序列化数据?我想有一个[device.name,history.transition date]的列表。尝试使用我在回答中添加的查询,它应该返回一个字典列表,如:
[{'history\u transition\u date':whatever,'name':whatever},{'history\u transition\u date':whater,'name':whater},