[Django]-Exclude Duplicate Objects in django queryset

5👍

StudentAppeared.objects.distinct()

sorry made a mistake. fixed it

2👍

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')
)

Leave a comment