QuerySet API Methods that do not return new QuerySets in Django ✅

data= User.objects.all()

<Queryset [<User: sandy sandy@gmail.com 123456789>, <User: rakesh rakesh@gmail.com 8888888888>, <User: Prasad prasad@gmail.com 7478747874>]>

get() - It returns one single object. If there is no result match it will raise DoesNotExist exception. If more than one item matches the get() query. It will raise MultipleObjects exception.

Example - Student.objects.get(pk=1)
Here pk is the primary key

first() - It returns the first object(row) matched by queryset. or None if there is no matching object. If the queryset has no ordering defined, then query set automatically  order by the primary key.

Example - Student.objects.first()

last() - It returns the last object(row) matched by queryset. or None if there is no matching object. If the queryset has no ordering defined, then query set automatically  order by the primary key.

Example - Student.objects.last()

latest() - It returns the latest object in table based on the given fields.

Example - Student.objects.latest('pass_date')

earliest() - It returns the earliest(old) object in table based on the given fields.

Example - Student.objects.earliest('pass_date')

exists() - It returns True if the queryset contains result.

Example - data = Student.objects.all()
print(data.exists()) - It returns True if queryset contain data.

Post a Comment

0 Comments