pythondjangodjango-modelsfilterdjango-database

django get to every user if its latest record match given value in table


I want to filter students if his last record transaction_type match with given value.

For example Student Ali has 3 record in transaction table. And if the latest records transaction_type == 'busy' I want to get this transaction otherwise I want to pass this transaction

My Models like that

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


Note: I use Postgres as Database Engine


Solution

  • One solution could be to get the latest records of all students and then check the 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'
    )