【问题标题】:Get the latest instance of a foreign key in django models获取 django 模型中外键的​​最新实例
【发布时间】:2020-07-27 01:28:00
【问题描述】:

您好,我在 Django ORM 中查询时遇到困难:

我有两个模型:

class Student(models.Model):
    name = models.CharField(max_length=200)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

class choices:
    CHOICES = {(0, "Present"),(1, "Absent")}

class Attendance(models.Model):
    student = models.ForeignKey(Student, on_delete=models.CASCADE,
                                                related_name='attendance')
    date = models.DateField()
    state = models.PositiveSmallIntegerField(choices=choices.CHOICES)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

我想知道所有在各自最新上课日期在场的学生。

【问题讨论】:

  • 我的最终目标是获取学生的查询集。包含学生对象的查询集可以按任意顺序排列,但每个学生对象在出勤表中的最新实例需要处于当前状态。 (我希望这是有道理的)
  • 你能解释一下使用一些字段吗?
  • @ArushSharma 如果学生在出勤表中没有任何条目怎么办?
  • 例如,有 3 名学生的 id 为 1,2,3。 1 于 2020 年 7 月 22 日在场,于 2020 年 7 月 23 日缺席。 2 于 2020 年 7 月 23 日缺席,2020 年 7 月 24 日存在,2020 年 7 月 19 日存在 3,2020 年 7 月 20 日存在。所以我想在查询集中有(2,3),因为它们出现在最近的日期(分别是 23/07/2020、24/07/2020、20/07/2020,对于 1,2,3)
  • @lain Shelvington 忽略那些学生。

标签: django django-models django-orm


【解决方案1】:

我有一个需要三个单独的数据库查询的解决方案

首先获取每个学生的最新Attendance id,并获取当前状态的最新Attendance id。

latest_attendances = Attendance.objects.order_by('student', '-date').distinct('student').values_list('id', flat=True)
latest_present_attendances = latest_attendances.filter(state=0)

使用set 算术,我们可以获得两者共有的所有Attendance id(最新和“当前”)

set(latest_attendances) & set(latest_present_attendances)

然后将其传递给Student 查询

Student.objects.filter(attendance__in=set(latest_attendances) & set(latest_present_attendances))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-11-29
    • 2011-01-05
    • 2012-05-07
    • 2016-10-24
    • 1970-01-01
    • 2018-04-25
    • 2020-06-17
    相关资源
    最近更新 更多