Django:查询数据库中每个类型的最新记录

2024-04-20 10:25:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在收集WiFi设备的数据,并存储MAC地址,以及在数据库中收集数据的时间。每个设备被检测多次,这意味着db表有多个具有相同MAC地址的行,但检测次数不同,如下所示:

DB Results

我想要的是,只获取每个MAC地址的最新检测结果。在上面的例子中,这将是:

  • 2018年11月17日上午6:17:02:e3:e6:b4:63:81
  • 2018年11月17日上午6:20:0a:13:0b:18:c0:5e
  • 2018年11月17日上午6:20:16:50:1d:82:cf:fa

如何过滤我的数据库查询来实现这样的功能?你知道吗

型号.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

Tags: djangonamefromimportnodetruetimeis
1条回答
网友
1楼 · 发布于 2024-04-20 10:25:04

除了你的评论,这里最简单的解决方法是提高效率。。。。只需使用groupby,因为它已经排序了,所以只需显示第一个结果。你知道吗

相关问题 更多 >