Django:查询数据库以获取每种类型的最新记录

时间:2018-11-18 23:13:45

标签: python django database

我正在收集有关启用WiFi的设备的数据,并存储MAC地址以及在数据库中收集数据的时间。每个设备都会被检测到多次,这意味着db表包含具有相同MAC地址但检测时间不同的多行,例如:

DB Results

我想要的是对每个MAC地址仅获取最新的检测。在上面的示例中,将是:

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

如何过滤数据库查询以实现类似的目的?

models.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)

views.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

1 个答案:

答案 0 :(得分:0)

这里最简单的解决方案是除了您的注释之外还有效率。...只需使用groupby,由于它已经排序,因此只显示第一个结果。