Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exclude Duplicate Objects in django queryset

I have model called StudentAppeared

class StudentAppeared(models.Model):
    roll_number = models.CharField(max_length=50)

Assume i have following data

enter image description here

From the above data result should display

enter image description here

How can i achieve this thing using django query for StudentAppeared model?

like image 957
Asif Avatar asked Sep 19 '26 03:09

Asif


2 Answers

StudentAppeared.objects.distinct()

sorry made a mistake. fixed it

like image 87
goromlagche Avatar answered Sep 22 '26 00:09

goromlagche


This returns unique roll_numbers with the highest associated id, sorted by id:

from django.db.models import Max

stats = (
    StudentAppeared.objects
    .values('roll_number')
    .annotate(max_id=Max('id'))
    .values_list('max_id', 'roll_number ')
    .order_by('max_id')
)
like image 35
Endre Both Avatar answered Sep 22 '26 00:09

Endre Both



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!