Interview question
What are Django Models and how do you use the ORM for database operations? Django Models क्या हैं और ORM का use करके database operations कैसे करते हैं?
Answer
Django Models are Python classes that define database table structure. The ORM (Object-Relational Mapping) abstracts SQL, allowing you to interact with database using Python code instead of writing raw SQL queries.
// Define Models
from django.db import models
from django.contrib.auth.models import User
class Category(models.Model):
name = models.CharField(max_length=100)
description = models.TextField()
created_at = models.DateTimeField(auto_now_add=True)
class Meta:
ordering = ['name']
verbose_name_plural = 'Categories'
def __str__(self):
return self.name
class Product(models.Model):
CATEGORY_CHOICES = [
('electronics', 'Electronics'),
('clothing', 'Clothing'),
('books', 'Books'),
]
name = models.CharField(max_length=200)
description = models.TextField()
price = models.DecimalField(max_digits=10, decimal_places=2)
category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='products')
quantity = models.IntegerField(default=0)
is_active = models.BooleanField(default=True)
created_by = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
ordering = ['-created_at']
indexes = [
models.Index(fields=['name', 'category']),
]
def __str__(self):
return self.name
// ORM Query Operations
from myapp.models import Product, Category
// CREATE
product = Product.objects.create(
name='Laptop',
price=999.99,
category_id=1,
quantity=50
)
// READ - Get single object
product = Product.objects.get(id=1) # Raises DoesNotExist if not found
product = Product.objects.filter(name='Laptop').first() # Returns None if not found
// READ - Get all objects
all_products = Product.objects.all()
// READ - Filter
active_products = Product.objects.filter(is_active=True)
expensive = Product.objects.filter(price__gte=1000)
cheap = Product.objects.filter(price__lt=100)
// READ - Complex queries
from django.db.models import Q
products = Product.objects.filter(
Q(name__icontains='phone') | Q(name__icontains='tablet'),
is_active=True
)
// UPDATE
product = Product.objects.get(id=1)
product.price = 1299.99
product.save()
// Bulk update
Product.objects.filter(category_id=1).update(price=F('price') * 1.1)
// DELETE
product.delete()
Product.objects.filter(quantity=0).delete()
// Aggregation
from django.db.models import Sum, Count, Avg
total_revenue = Product.objects.aggregate(Sum('price'))
product_count = Product.objects.count()
avg_price = Product.objects.aggregate(Avg('price'))
// Grouping
from django.db.models import Sum
category_stats = Product.objects.values('category').annotate(
total_products=Count('id'),
avg_price=Avg('price')
)
// Ordering
products_asc = Product.objects.order_by('name')
products_desc = Product.objects.order_by('-created_at')
// Slicing
first_10 = Product.objects.all()[:10]
page_2 = Product.objects.all()[10:20]
// Relationships
# Get products in a category
category = Category.objects.get(id=1)
category_products = category.products.all()
# Get category of a product
product = Product.objects.get(id=1)
category = product.categoryDjango Models और ORM:
Model: Python class = Database table
Field: Class attribute = Table column
Field Types:
- CharField: Text (fixed length)
- TextField: Long text
- IntegerField: Numbers
- DecimalField: Decimal numbers
- DateTimeField: Date और time
- BooleanField: True/False
- ForeignKey: Relationships
- ManyToManyField: Many-to-many
ORM Operations:
Create:
Product.objects.create(name='Item', price=100)
Read:
Product.objects.all() # सभी
Product.objects.filter(id=1) # Filter
Product.objects.get(id=1) # Single
Update:
product.price = 200
product.save()
Delete:
product.delete()
ORM Advantages:
- SQL नहीं लिखना पड़ता
- Database-agnostic
- SQL injection से safe
- Relationships handle होते हैंWas this answer clear?