首页 \ 问答 \ a怎么能在django中做一个“最大n组”查询?(How can a do a “greatest-n-per-group” query in django?)

a怎么能在django中做一个“最大n组”查询?(How can a do a “greatest-n-per-group” query in django?)

(这是SQL连接的线程的Django版本:在一对多关系中选择最后的记录

假设我有一张客户表和一张购买表。 每笔购买都属于一个客户。 我想获得所有客户的列表以及他们最后一次购买。 它可以在没有原始SQL和没有多个数据库查询的情况下完成?


(This is the django version of the thread at SQL join: selecting the last records in a one-to-many relationship)

Suppose I have a table of customers and a table of purchases. Each purchase belongs to one customer. I want to get a list of all customers along with their last purchase. Can it be done without raw SQL and without multiple database queries?


原文:https://stackoverflow.com/questions/2111590
更新时间:2023-06-21 15:06

最满意答案

寻找现场主持人

确保获得所有实时主机的最佳方法是使用nmap工具对子网进行ping扫描。 由于Windows主机默认不响应ping,因此它还包括简短的TCP端口扫描。 linux CLI的语法是nmap -sP 192.0.2.0/24 (替换你的子网而不是192.0.2.0/24)。

SNMP查询

我不认为SNMP会真正解决您的问题,但我将包括我可以提供的帮助...当您使用PHP SNMP扩展时 ,您首先需要知道具有正确信息的表的OID。 LANCOM-1711-MIB是一种可能性,但很难确定; 如果您不知道要轮询哪个SNMP OID,请联系LANCOM支持。

让我们假设staDhcpLanIpadd (OID:1.3.6.1.4.1.2356.500.2.1712.1.32.21.1.2)是您需要的OID。 此时,您将使用SNMPv2c和您在其上配置的SNMP社区来snmpwalk路由器。 据推测,这个OID为您提供了已发布的DHCP地址列表; 但是,这并不意味着它们在您轮询路由器时就已存在(有人可能拔掉了电缆或将其关闭)。


So I wrote a script that probes the Lancom router and pulls out the DHCP/BOOTP table. It may be used for all those who need to monitor such routers, and therefore I am sharing it. It also outputs a nice HTML table; the function BetterTable() can be used on any 2D array.

You will need to set IP, userid, and pwd (first three variables) in order to use the script on your router.

    <?php

    $router_ip = '';
    $username = '';
    $password = '';
    $port = 23;
    $timeout = 10;

    $connection = fsockopen($router_ip, $port, $errno, $errstr, $timeout);

    if(!$connection){
     echo "Connection failed\n";
     exit();
    } else {

     fputs($connection, "$username\r\n");
     fputs($connection, "$password\r\n");
     fputs($connection, "cd setup/dhcp/dhcp-table \r\n");
     fputs($connection, "dir \r\n");
     fputs($connection, " ");

     $j = 0;
     while ($j < 16) {
      fgets($connection);
      $j++;
     }
     stream_set_timeout($connection, 2);
     $timeoutCount = 0;
     $content ='';
     $DhcpArray = '';
     (int) $index =0;

    $DhcpFile = "C:\IP-Symcon\webfront\user\images\LancomDhcp.txt";
    $fh = fopen($DhcpFile, 'w') or die("can't open file");

    //$DhcpArray[0] = array ('IP-Address', 'MAC-Address', 'Timeout', 'Hostname', 'Type', 'LAN-Ifc', 'Ethernet-Port', 'VLAN-ID', 'Network-Name');

     while (!feof($connection)){

      $content = fgets($connection);
      $content = str_replace("\r", '', $content);
      $content = str_replace("\n", "", $content);
      $lineArray = explode(' ', $content); 
      if (isValidIp($lineArray [0]))
          { 
          $DhcpArray[$index]['IP-Address'] = substr ($content, 0,17);
          $DhcpArray[$index]['MAC-Address'] = substr ($content, 17,32-18);
          $DhcpArray[$index]['Timeout'] = substr ($content, 31,41-32);
          $DhcpArray[$index]['Hostname'] = substr ($content, 40,108-41);
          $DhcpArray[$index]['Type'] = substr ($content, 107,125-108);
          $DhcpArray[$index]['LAN-Ifc'] = substr ($content, 124,137-125);
          $DhcpArray[$index]['Ethernet-Port'] = substr ($content, 136,152-137);
          $DhcpArray[$index]['VLAN-ID'] = substr ($content, 151,161-152);
          $DhcpArray[$index]['Network-Name'] = substr ($content, 160);
          fwrite($fh, $content);
          $index +=1;
          }

      # If the router say "press space for more", send space char:
      if (preg_match('/MORE/', $content) ){ // IF current line contain --More-- expression,
       fputs ($connection, " "); // sending space char for next part of output.
      } # The "more" controlling part complated.

      $info = stream_get_meta_data($connection);
      if ($info['timed_out']) { // If timeout of connection info has got a value, the router not returning a output.
       $timeoutCount++; // We want to count, how many times repeating.
      }
      if ($timeoutCount >2){ // If repeating more than 2 times,
       break;   // the connection terminating..
      }
     }
     $content = substr($content,410);

     BetterTable($DhcpArray);




    fclose($fh);

    }
    echo "End.\r\n";

    //--------------------------------------------------------------------

    function isValidIp($ip)
    {/* PCRE Pattern written by Junaid Atari */
        return !preg_match ( '/^([1-9]\d|1\d{0,2}|2[0-5]{2})\.('.
                             '(0|1?\d{0,2}|2[0-5]{2})\.){2}(0|1?'.
                             '\d{0,2}|2[0-5]{2})(\:\d{2,4})?$/',
                             (string) $ip )
                ? false
                : true;
    }

    //--------------------------------------------------------------

    function BetterTable($twoDimArray)
    {
    $i = 0;
    echo "<table>
            <table class='BetterTable' border='1'>";

    echo "<tr>";
    echo '<td>Line #
    </td>';
    foreach ($twoDimArray[0] as  $fieldName => $fieldValue)
        {
            echo '<td>'.$fieldName. '</td>';
        }echo '</tr>';
    $i = 0;

    foreach ($twoDimArray as $rowName => $rowValue) 
    {
            if ($i%2 == 0) 
                Echo "<tr bgcolor=\"#d0d0d0\" >";
            else 
                Echo "<tr bgcolor=\"#eeeeee\">";
        $fields = count($twoDimArray[$i]);
        $y = 0;
        echo '<td>'.$i. '</td>';
        foreach ($rowValue as  $fieldName => $fieldValue)
        {
            echo '<td>'.$fieldValue. '</td>';
            $y = $y + 1;
        }
        echo '</tr>';
        $i = $i + 1;
    }


    echo '</table>';
    }


    ?>

相关问答

更多
  • 你不能。 MAC地址是以太网的东西,而不是Internet的东西。 机器甚至可能没有任何使用MAC地址的接口。 You can't. MAC addresses are Ethernet things, not Internet things. The machine might not even have any interfaces that use MAC addresses.
  • 寻找现场主持人 确保获得所有实时主机的最佳方法是使用nmap工具对子网进行ping扫描。 由于Windows主机默认不响应ping,因此它还包括简短的TCP端口扫描。 linux CLI的语法是nmap -sP 192.0.2.0/24 (替换你的子网而不是192.0.2.0/24)。 SNMP查询 我不认为SNMP会真正解决您的问题,但我将包括我可以提供的帮助...当您使用PHP SNMP扩展时 ,您首先需要知道具有正确信息的表的OID。 LANCOM-1711-MIB是一种可能性,但很难确定; 如果您不 ...
  • 在LAN上发现应用程序的运行实例通常使用UDP广播来完成。 请求应用程序在预定端口上向LAN的子网广播IP发送单个请求消息,该端口将消息复制到连接到该子网的每台PC上的该端口。 您的其他应用可以在该端口上打开UDP侦听套接字以接收请求。 当每个应用程序收到请求时,它将拥有请求者的IP并可以直接向其发送回复,从而允许请求者发现回复者。 发送初始请求后,请求者可以等待一段时间收集它收到的任何回复,然后根据需要使用该信息。 Discovering running instances of your app on ...
  • 是。 有可能的。 安装PHP并在LAN上的一台计算机上配置PHP应用程序。 我们称这台机器为myserver.local 。 然后在同一个工作站上测试应用程序,以确保它正常工作。 您可能正在使用这样的URL: http://localhost/appname/index.php 一旦你确定它工作正常,那么你可以使用以下方法从局域网中的其他计算机访问应用程序: http://myserver.local/appname/index.php 希望这可以帮助。 Yes. It is possible. Ins ...
  • 使用phpinfo()来检查你的服务器的PHP二进制文件是否支持SNMP。 如果是这样,你可以这样做:
  • 你已经使用--skip-broken标志安装了php-snmp。 很可能存在依赖性问题,您已跳过该问题。 作为一个拇指规则,避免完全使用跳过 You have installed php-snmp with the --skip-broken flag. It is very likely that there was a dependency issue, which you have skipped. As a rule of thumbs, avoid using skip-broken comple ...
  • 这取决于您是否需要根据mib实例或mib数据选择数据。 您可以根据实例选择数据,例如: snmpwalk -v2c -cpublic 1.2.3.4 ifOperStatus 这将为您提供设备中的所有接口状态。 SNMP不支持仅获取ifOperStatus =“up”,在这种情况下,您需要检索所有实例并进行选择 snmpwalk -v2c -cpublic 1.2.3.4 ifOperStatus | grep up 另一个顶级解决方案是收集数据并将其存储在数据库中,然后您可以使用您在问题中提到的S ...
  • 大多数网络设备都支持SNMP,包括许多WLAN接入点。 但是,您的问题无法以StackOverflow的格式回答。 SNMP是一种“分散式”协议,每个设备供应商都可以确切地决定设备应该实现哪些功能。 供应商发布MIB(管理信息库)模块,描述可以监视哪些变量。 每个设备都可以实现任意数量的MIB模块,包括作为Internet标准发布的模块。 当然,SNMP将成为任何企业级网络管理解决方案的核心部分,但对于如此庞大的网络,您所需要的可能是一名优秀的技术顾问(或者更好,聘请具有网络管理经验的人员)。 或者,预留几 ...
  • 问题的第一部分是小数秒。 此外,时区不是我们可以支持的形式(我们只能做很多事情;我们专注于使解析器能够处理ISO时间戳格式的公共部分)。 但是,这确实意味着我们可以相当容易地清理。 这有几个步骤,我们将使用正则regexp , scan和format来帮助: # Your example, in a variable for my convenience set instant "2016-10-3,2:15:27.0,-4:0" # Take apart the problem piece; REs a ...

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)