django获取每个用户,如果它的最新记录匹配表中的给定值

3duebb1j  于 2023-02-14  发布在  Go
关注(0)|答案(1)|浏览(111)

如果学生的最后一条记录transaction_type与给定值匹配,我想过滤学生。
例如,学生阿里在事务表中有3条记录。如果最新记录transaction_type == '忙碌',则我想获取此事务,否则我想传递此事务
我的模特们喜欢这样

class Type(models.Model):
    type = models.CharField(max_length=50)

    def __str__(self):
        return self.durum

class Student(models.Model):
    ogr_no = models.CharField(max_length=10, primary_key=True)
    ad = models.CharField(max_length=50)
    soyad = models.CharField(max_length=50)
    bolum = models.CharField(max_length=100,blank=True)
    dogum_yeri = models.CharField(max_length=30)
    sehir = models.CharField(max_length=30)
    ilce = models.CharField(max_length=30)
    telefon = models.CharField(max_length=20,blank=True, null=True)
    nufus_sehir = models.CharField(max_length=30,blank=True, null=True)
    nufus_ilce = models.CharField(max_length=30,blank=True, null=True)

    def __str__(self):
        return  self.ogr_no + " " + self.ad + " " + self.soyad 

class Transaction(models.Model):
    student = models.ForeignKey(Student, on_delete=models.CASCADE, related_name='islemogrenci')
    transaction_type = models.ForeignKey(Type, on_delete=models.CASCADE)
    yardim = models.ForeignKey(Yardim, on_delete=models.CASCADE, blank=True, null=True)
    aciklama = models.CharField(max_length=300,blank=True, null=True)
    transaction_date = models.DateTimeField(blank=True,null=True)
    transaction_user = models.ForeignKey(User, on_delete=models.CASCADE,null=True,blank=True)

    def __str__(self):
        return self.student.ad + " " + self.transaction_type.durum

注意:我使用Postgres作为数据库引擎

n9vozmp4

n9vozmp41#

一种解决方案是获取所有学生的最新记录,然后检查transaction_type

latest_records = Transaction.objects.values('student').annotate(
    latest_record=Max('id')
)

transactions = Transaction.objects.filter(
    id__in=latest_records.values('latest_record'),
    transaction_type='busy'
)

相关问题