Django Get First Record Example

Published On: 04/08/2022 | Category: Django

Hi Friends,

In this post, we will learn django get first record. you will learn django get first record in queryset. I would like to show you how to get first inserted record in django. I would like to show you django get first record id. So, let's follow few step to create example of django get first record by id.

In this tuts, There are several ways to django get last record. we will use first() and arr slicing functions to get first record from database. so let's see the below examples.

let's see below simple example with output:

Example 1:

In this example returns the first User in the table, according to the id field:

views.py
from django.shortcuts import render
from django.http import HttpResponse
from django.contrib.auth.models import User

def index(request):
    user = User.objects.first()
    print(user)
    return HttpResponse(user)
Output
<User: bhavesh>
Example 2:

In this example returns the firstUser in the table, according to the id field:

views.py
from django.shortcuts import render
from django.http import HttpResponse
from django.contrib.auth.models import User

def index(request):
    user = User.objects.all()[:1].get()
    print(user)
    return HttpResponse(user)
Output
<User: bhavesh>

I Hope It will help you....