Paramclasses Academy - Blog

Tutorials Details

Django Models and Database Basics: Complete Guide with Practical Examples

Django Models and Database Basics: Complete Guide with Practical Examples

October 19, 2026

Django Models and Database Basics: Complete Guide with Practical Examples

1. Introduction to Django Models

Django Model एक Python class होती है जो database table की structure define करती है। इसके fields बताते हैं कि table में किस प्रकार का data store होगा।

उदाहरण के लिए, Student Management System में student का नाम, email, phone और course database में store करना हो, तो हम एक Student model बना सकते हैं।

Django Models के मुख्य फायदे:

  • Database table की structure Python code से define करना।

  • Data create, read, update और delete करना।

  • Database queries के लिए Django ORM का उपयोग करना।

  • Migrations से database schema में बदलाव लागू करना।

  • SQL queries manually लिखने की जरूरत कम करना।

2. Django Model बनाने से पहले

मान लीजिए project का नाम school_project और app का नाम students है।

यदि app अभी नहीं बनाया है, तो terminal में चलाएं:

python manage.py startapp students

अब school_project/settings.py में app को INSTALLED_APPS में शामिल करें:

INSTALLED_APPS = [
    # Django default apps
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    # Custom app
    'students',
]

यदि app पहले से मौजूद है और registered है, तो उसे दोबारा add न करें।

3. पहला Django Model बनाना

students/models.py file खोलें और यह code लिखें:

from django.db import models


class Student(models.Model):
    name = models.CharField(max_length=100)
    email = models.EmailField(unique=True)
    phone = models.CharField(max_length=15)
    course = models.CharField(max_length=100)
    city = models.CharField(max_length=100)
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.name

Code को समझें

  • models.Model: बताता है कि यह Django model है।

  • name: student का नाम store करेगा।

  • CharField: text store करने के लिए उपयोग होता है।

  • max_length=100: text की अधिकतम लंबाई निर्धारित करता है।

  • EmailField: email address के लिए उपयोग होता है।

  • unique=True: email की duplicate value database में रोकता है।

  • DateTimeField: date और time store करता है।

  • auto_now_add=True: record पहली बार create होने पर timestamp set करता है।

  • __str__(): admin और debugging में object का readable नाम दिखाने में मदद करता है।

यह model database में table की structure बनाने के लिए तैयार है, लेकिन table बनाने के लिए migrations चलानी होंगी।

4. Django Migrations क्या हैं?

Migrations, models में किए गए बदलावों को database schema पर लागू करने का तरीका हैं।

जब आप model बनाते या update करते हैं, तो Django को उन बदलावों को migration file में record करना और फिर database में apply करना होता है।

Step 1: Migration file बनाएं

python manage.py makemigrations

यह model changes को migration files में तैयार करता है।

Step 2: Database में बदलाव लागू करें

python manage.py migrate

यह pending migrations को database में apply करता है।

Step 3: Migration status देखें

python manage.py showmigrations

इससे पता चलता है कि कौन-सी migrations apply हुई हैं।

याद रखें: makemigrations migration files बनाता है, जबकि migrate उन बदलावों को database पर लागू करता है।

5. Django ORM क्या है?

ORM का पूरा नाम Object-Relational Mapping है। Django ORM की मदद से Python code से database records को manage किया जा सकता है।

उदाहरण के लिए, SQL में student records प्राप्त करने के लिए query लिखने के बजाय आप लिख सकते हैं:

Student.objects.all()

यह Student model के records प्राप्त करने के लिए QuerySet देता है।

ORM के मुख्य फायदे:

  • Python syntax में database queries लिखना।

  • Database operations को models के साथ व्यवस्थित रखना।

  • Create, read, update और delete करना।

  • Filtering और sorting करना।

  • Related models के साथ काम करना।

6. Django Admin में Model Register करना

Django Admin से student records manage करने के लिए students/admin.py file में लिखें:

from django.contrib import admin
from .models import Student


@admin.register(Student)
class StudentAdmin(admin.ModelAdmin):
    list_display = ('id', 'name', 'email', 'course', 'city')
    search_fields = ('name', 'email', 'course')
    list_filter = ('course', 'city')

इसके बाद superuser बनाएं:

python manage.py createsuperuser

Terminal के instructions के अनुसार username, email और password set करें।

Server start करें:

python manage.py runserver

Browser में खोलें:

http://127.0.0.1:8000/admin/

Login करने के बाद Student model से records add, view, edit और delete किए जा सकते हैं।

ध्यान दें: यदि model अभी-अभी बनाया है, तो Admin में दिखाई देने से पहले migrations apply करना जरूरी है।

7. Database में Data Create करना

Django shell खोलें:

python manage.py shell

अब shell में:

from students.models import Student

student = Student.objects.create(
    name="Rahul Sharma",
    email="rahul@example.com",
    phone="9876543210",
    course="Django Development",
    city="Raipur"
)

print(student.id)
print(student.name)

objects.create() record create करके save भी कर देता है।

Email field पर unique=True होने के कारण वही email दोबारा create करने पर database constraint error आ सकता है।

8. Database से Data Read करना

सभी students प्राप्त करना

students = Student.objects.all()

for student in students:
    print(student.name, student.course)

एक student को ID से प्राप्त करना

student = Student.objects.get(id=1)

print(student.name)

get() को matching record नहीं मिलने पर Student.DoesNotExist error हो सकता है। एक से ज्यादा matching records होने पर भी error आता है।

Filter करके records प्राप्त करना

students = Student.objects.filter(city="Raipur")

Course के अनुसार filter करना

students = Student.objects.filter(
    course="Django Development"
)

Records को sort करना

students = Student.objects.order_by('name')

Descending order:

students = Student.objects.order_by('-name')

9. Database में Data Update करना

ID 1 वाले student का city update करने का उदाहरण:

student = Student.objects.get(id=1)

student.city = "Bilaspur"
student.save()

यहाँ save() बदलाव को database में persist करता है।

यदि record मौजूद न हो, तो get() error देगा। Real applications में इस स्थिति को संभालना चाहिए।

10. Database से Data Delete करना

किसी student record को delete करने का उदाहरण:

student = Student.objects.get(id=1)

student.delete()

सावधानी: delete() वास्तविक record हटा देता है। सीखने के दौरान test database का उपयोग करें और production data delete करने से पहले backup तथा authorization सुनिश्चित करें।

11. Django Model Field Types

कुछ common field types:

Field उपयोग
CharField सीमित लंबाई का text
TextField लंबा text
IntegerField पूर्णांक
BooleanField True/False value
EmailField Email address
DateField Date
DateTimeField Date और time
DecimalField Fixed-precision decimal values
FloatField Floating-point number
ForeignKey दूसरे model से many-to-one relation
FileField File upload reference
ImageField Image upload reference

Field चुनते समय data की प्रकृति और validation requirements को ध्यान में रखें।

उदाहरण के लिए, phone number को अक्सर CharField में रखना बेहतर होता है, क्योंकि उसमें leading zero या + country code हो सकता है।

12. Django Model में Relationships की Basic समझ

कई applications में एक table दूसरे table से जुड़ी होती है।

उदाहरण: एक course में कई students enroll हो सकते हैं।

from django.db import models


class Course(models.Model):
    title = models.CharField(max_length=100)

    def __str__(self):
        return self.title


class EnrolledStudent(models.Model):
    name = models.CharField(max_length=100)
    course = models.ForeignKey(
        Course,
        on_delete=models.CASCADE,
        related_name='students'
    )

    def __str__(self):
        return self.name

यहाँ ForeignKey relationship बनाता है।

on_delete=models.CASCADE का अर्थ है कि related Course delete होने पर उससे जुड़े EnrolledStudent records भी delete किए जाएंगे। वास्तविक application में यह व्यवहार सोच-समझकर चुनें।

यह उदाहरण अलग-अलग models का परिचय देता है। अपने project में model names और relationships को application की वास्तविक जरूरत के अनुसार रखें।

13. Common Django Model और Database Errors

Error 1: No changes detected

संभावित कारण:

  • Model में कोई नया बदलाव नहीं है।

  • App INSTALLED_APPS में नहीं है।

  • Model गलत file में लिखा गया है।

समाधान: models.py और INSTALLED_APPS check करें, फिर makemigrations चलाएं।

Error 2: no such table

कारण: Database table अभी बनी नहीं है या migration apply नहीं हुई।

समाधान:

python manage.py makemigrations
python manage.py migrate

Error 3: IntegrityError

कारण: Unique field में duplicate value डालना या database constraint का उल्लंघन करना।

समाधान: Duplicate data check करें और application में उचित validation लगाएं।

Error 4: DoesNotExist

कारण: get() से मांगा गया record नहीं मिला।

समाधान: filter() या get_object_or_404() जैसे विकल्पों पर विचार करें।

View का उदाहरण:

from django.shortcuts import get_object_or_404
from .models import Student


def student_detail(request, student_id):
    student = get_object_or_404(Student, id=student_id)

    # आगे template render करें

इस snippet में view का अंतिम response अभी जोड़ना बाकी है; यह केवल record lookup का उदाहरण है।

Error 5: Model Admin में नहीं दिख रहा

समाधान:

  • Model को admin.py में import और register करें।

  • Migrations apply करें।

  • सही Django project और database का उपयोग कर रहे हैं, यह verify करें।

14. Frequently Asked Questions (FAQs)

Q1. Django Model क्या है?

Django Model एक Python class है जो database में store होने वाले data और उसकी structure को define करती है।

Q2. Migration क्या है?

Migration model changes को database schema में लागू करने के लिए Django द्वारा उपयोग की जाने वाली system है।

Q3. ORM क्या है?

ORM Python objects और database records के बीच काम करने का तरीका देता है, जिससे कई database operations Python code से किए जा सकते हैं।

Q4. makemigrations और migrate में क्या अंतर है?

makemigrations changes की migration files बनाता है। migrate pending migrations database में apply करता है।

Q5. __str__() क्यों लिखते हैं?

यह model object का readable text representation देता है, जैसे Student object के लिए उसका नाम।

Q6. filter() और get() में क्या अंतर है?

filter() matching records का QuerySet देता है, जो खाली भी हो सकता है। get() एक ही matching record अपेक्षित करता है और record न मिलने या multiple records मिलने पर exception दे सकता है।

Q7. Django Admin क्या है?

Django Admin एक built-in interface है जिससे authorized users registered models के records manage कर सकते हैं।

Q8. क्या Django केवल SQLite support करता है?

नहीं। Django SQLite, PostgreSQL, MySQL और Oracle जैसे databases को support करता है। सही configuration और supported versions आवश्यक हैं।

15. Important Django Interview Questions and Answers

Q1. Django Model क्या होता है?

एक Python class जो database data की structure और fields define करती है।

Q2. Django ORM का पूरा नाम क्या है?

Object-Relational Mapping.

Q3. objects.all() क्या करता है?

Model के सभी available records के लिए QuerySet देता है।

Q4. objects.filter() क्या करता है?

दिए गए conditions से match करने वाले records का QuerySet देता है।

Q5. save() का क्या काम है?

Model instance को database में save या उसके बदलावों को persist करने के लिए उपयोग होता है।

Q6. delete() क्या करता है?

Model instance या QuerySet से जुड़े database records को delete करता है।

Q7. ForeignKey क्यों उपयोग करते हैं?

दो models के बीच many-to-one relationship define करने के लिए।

Q8. unique=True क्या करता है?

Field के लिए unique constraint निर्धारित करता है, ताकि duplicate values database constraint के अनुसार रोकी जा सकें।

Q9. Django Admin में model कैसे दिखाते हैं?

Model को admin.py में import करके admin.site.register() या @admin.register() से register करते हैं।

Q10. Migration files क्यों जरूरी हैं?

वे model changes का versioned record रखती हैं और database schema को उन changes के अनुसार update करने में मदद करती हैं।

16. Practical Assignment

एक Student Management System के लिए:

  1. students app बनाएं और उसे INSTALLED_APPS में add करें।

  2. Student model बनाएं।

  3. Name, email, phone, course, city और created date fields जोड़ें।

  4. Model में __str__() method लिखें।

  5. makemigrations और migrate चलाएं।

  6. Model को Django Admin में register करें।

  7. Superuser बनाकर कम-से-कम तीन sample students add करें।

  8. Django shell से सभी records retrieve करें।

  9. filter() से किसी एक city के students निकालें।

  10. एक student का city update करें और test database में delete operation भी आजमाएं।

17. Conclusion

इस module में आपने Django Models, field types, migrations, ORM, database CRUD operations, Django Admin और model relationships की basics सीखीं।

अब आप Django application में structured data store और manage करने की दिशा में आगे बढ़ सकते हैं।

अगले module में हम Django Forms and Form Validation सीखेंगे, जहाँ HTML forms से user input लेना और उसे validate करना समझेंगे।