我正在收集WiFi设备的数据,并存储MAC地址,以及在数据库中收集数据的时间。每个设备被检测多次,这意味着db表有多个具有相同MAC地址的行,但检测次数不同,如下所示:
我想要的是,只获取每个MAC地址的最新检测结果。在上面的例子中,这将是:
如何过滤我的数据库查询来实现这样的功能?你知道吗
型号.py
from django.db import models
"""
Node is a Pi Zero. Each time one of these is found, we want to display it
as a map marker
"""
class Node(models.Model):
# A human readable name for the node
name = models.CharField(max_length=30, default='Pi Zero')
mac_address = models.CharField(max_length=30, primary_key=True)
time = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.name
"""
Device is a WiFi enabled devices. The Pi Zeros
discover new Devices and feed that information to the mesh network sink. The
sink node then makes a POST request to this webapp that instantiates an instance
of this model.
This data is displayed on the map and is associated with each Node Model.
"""
class Device(models.Model):
discovered_by = models.ForeignKey(Node, on_delete=models.CASCADE)
mac_address = models.CharField(max_length=18)
age = models.IntegerField(default=0)
vendor = models.CharField(max_length=60, blank=True)
time = models.DateTimeField(auto_now_add=True)
视图.py:
from django.shortcuts import render
from django.views import generic
# from django.views.generic import edit
from apps.main.models import Node, Device
from django.conf import settings
class HomeView(generic.TemplateView):
template_name = 'index.html'
def nodes(self):
nodes = Node.objects.all()
for node in nodes:
node.devices = Device.objects.filter(discovered_by=node).order_by('mac_address', '-time')
return nodes
除了你的评论,这里最简单的解决方法是提高效率。。。。只需使用
groupby
,因为它已经排序了,所以只需显示第一个结果。你知道吗相关问题 更多 >
编程相关推荐