Django Query Set

1 Customer.objecs.all()
2 Customer.objecs.first()
3 Customer.objecs.last()
4 Customer.objecs.get(id=3)
5 Customer.objecs.filter(id=3)
6 Customer.objecs.exclude(id=3)
7 How to write a subuery?
ids = Employee.objects.filter(company='Private').values_list('id', flat=True) Person.objects.filter(id__in=ids).values('name', 'age') OR from django.db.models import OuterRef, Subquery newest = Comment.objects.filter(post=OuterRef('pk')).order_by('-created_at') Post.objects.annotate(newest_commenter_email=Subquery(newest.values('email')[:1]))
8 How to write a group query?
from django.db.models import Count Transaction.objects.all().values('actor').annotate(total=Count('actor')).order_by('total') =====With Where========== Transaction.objects.filter(name='kk').values('actor').annotate(total=Count('actor')).order_by('total') =====With User Table========== from django.contrib.auth.models import User from django.db.models import Count User.objects.filter(is_staff=True).values('is_active').annotate(cnt=Count('is_active')).order_by('id') ===== Group of Two field==== User.objects.values('is_active','is_staff').annotate(total_count=Count('id')) ==== Group by expression ===== Employee.objects.values('joining_date__year').annotate(total_count=Count('id')) ==== Group by Distinct ===== Customer.objects.values('country').annotate(count=Count('id'),unique_names=Count('country',distinct=True))
9 How to write a AVG,MIN MAX query?
from myApp.models import Employee from django.db.models import Avg, Min, Max queryset = Employee.objects.aggregate(Avg('salary')) queryset = Employee.objects.aggregate(Min('salary')) queryset = Employee.objects.aggregate(Max('salary'))
X