Django:按ID [多对一关系]获取最后一条记录

编程入门 行业动态 更新时间:2024-10-26 22:27:53
本文介绍了Django:按ID [多对一关系]获取最后一条记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试使用Django模型中的多对一关系将一个表中的最后一条记录连接到另一个表.这是我的Django模型:

I'm trying to get the last record in one table connected to another one using many-to-one relationship in django models. Here's my django models:

class DataCollecttion(models.Model): default_name = models.CharField(max_length=100) class NameHistory(models.Model): old_name = models.CharField(max_length=100) collection_data = models.ForeignKey(DataCollection, on_delete=models.CASCADE, null=True)

在这里,我为 DataCollection 表创建了一个示例数据:

Here I created a sample data for DataCollection table:

这是 NameHistory 表的示例数据:

我在这里想要过滤或获取每个 collection_data_id 中的 NameHistory 中的最后一条记录(红色矩形内的记录),并将其显示在我的视图中.简而言之,我想获得这些行以及如何在ORM查询中做到这一点:

What I want here is to filter or get the last record in NameHistory in each collection_data_id (the records inside the red rectangle) and display it in my views. So in short I want to get these lines and how can I do it in ORM Query:

sample3 test2 data1

推荐答案

是否需要窗口功能:

窗口函数提供了一种在分区上应用函数的方法.窗口函数不同于普通的聚合函数,它为group by定义的每个集合计算最终结果,而窗口函数则对帧和分区进行运算,并为每一行计算结果.

Window functions provide a way to apply functions on partitions. Unlike a normal aggregation function which computes a final result for each set defined by the group by, window functions operate on frames and partitions, and compute the result for each row.

对于您的架构设计:

from django.db.models import F, Window from django.db.models.functions.window import FirstValue ( DataCollecttion .objects .annotate( first_old_name=Window( expression=FirstValue('namehistory__old_name'), partition_by=[F('id'), ], order_by=F('namehistory__id').desc() ) ) .values_list('first_old_name', flat=True) .distinct() )

这应该返回预期的列表.

This should return the expected list.

更多推荐

Django:按ID [多对一关系]获取最后一条记录

本文发布于:2023-10-20 13:00:45,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1511038.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:关系   Django   ID

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!