Django Models ORM Interview Questions
Django Models ORM Interview Questions
Answer: A model in Django is a Python class that defines the structure of your database
tables. It represents the data structure of your application and defines the fields and
behavior of the data you are storing. Each model class is mapped to a database table.
Answer: To create a model in Django, define a Python class that inherits from
django.db.models.Model. The class attributes define the fields in the database.
python
CopyEdit
from django.db import models
class Book(models.Model):
title = models.CharField(max_length=100)
author = models.CharField(max_length=100)
published_date = models.DateField()
def __str__(self):
return self.title
Answer: The __str__ method in a Django model is used to define the string
representation of the model instances. It’s helpful when you work with model instances in
Django Admin or other areas of your application, as it shows a readable version of the
object.
Answer:
Answer:
Answer: A migration in Django is a way to apply changes made to the models (like
adding or modifying fields) to the database schema. Migrations are automatically
generated when you create or change models and are applied to the database to sync the
changes.
Answer: Model managers are custom query sets that allow you to define custom
database queries in the model. They can be used to encapsulate common queries.
python
CopyEdit
class Book(models.Model):
title = models.CharField(max_length=100)
author = models.CharField(max_length=100)
Answer:
Answer: The get() method retrieves a single record from the database based on a given
condition. If more than one record is found, it raises a MultipleObjectsReturned
exception, and if no record is found, it raises a DoesNotExist exception.
Example:
python
CopyEdit
book = Book.objects.get(id=1)
Answer: The filter() method allows you to apply conditions to the query and retrieve
specific records.
Example:
python
CopyEdit
books = Book.objects.filter(author='J.K. Rowling')
Answer: The exclude() method is the opposite of filter(). It returns all records
except those that match the specified condition.
Example:
python
CopyEdit
books = Book.objects.exclude(author='J.K. Rowling')
14. How do you use annotate() in Django ORM?
Answer: annotate() is used to calculate and add values to each object in the queryset.
It’s often used for aggregate calculations like sums or averages.
Example:
python
CopyEdit
from django.db.models import Count
books = Book.objects.annotate(num_reviews=Count('reviews'))
Example:
python
CopyEdit
class Book(models.Model):
title = models.CharField(max_length=100)
author = models.CharField(max_length=100)
class Meta:
indexes = [
models.Index(fields=['title']),
]
Answer: Constraints in Django are used to ensure data integrity. Some common
constraints are:
unique: Ensures that the field value is unique across the database.
null: Specifies whether the field can be null.
blank: Specifies whether the field is allowed to be blank in forms.
choices: Restricts the field value to a predefined set of values.
Example:
python
CopyEdit
class Book(models.Model):
title = models.CharField(max_length=100)
class Review(models.Model):
book = models.ForeignKey(Book, on_delete=models.CASCADE)
review_text = models.TextField()
Example:
python
CopyEdit
books = Book.objects.select_related('author').all()
Example:
python
CopyEdit
books = Book.objects.prefetch_related('reviews').all()
Answer: You can update a record by retrieving the object, modifying the fields, and then
saving it.
Example:
python
CopyEdit
book = Book.objects.get(id=1)
book.title = 'New Title'
book.save()
21. What is a Manager in Django, and how do you use it?
Answer: A Manager in Django is the default interface for database query operations. It
allows you to query the database and provides methods like all(), filter(), get(),
etc. You can create custom managers to encapsulate query logic specific to your models.
Example:
python
CopyEdit
class PublishedBooksManager(models.Manager):
def published(self):
return self.filter(status='published')
class Book(models.Model):
title = models.CharField(max_length=100)
status = models.CharField(max_length=10)
22. What is the difference between save() and update() methods in Django ORM?
Answer:
save(): This method is used to create a new record or update an existing record in
the database. If the object already exists, Django will perform an UPDATE; if it doesn’t
exist, it will perform an INSERT.
update(): This method is used specifically to update one or more fields of a model,
and it doesn’t call the save() method or run any model’s save signal.
Example:
python
CopyEdit
book = Book.objects.get(id=1)
book.title = 'Updated Title'
book.save() # This will update the record in the database
Book.objects.filter(author='Author').update(status='published') #
Directly updates without calling save()
Answer: Django signals are used to allow certain senders to notify a set of receivers
when certain actions have occurred. They are typically used to perform operations
automatically when events like pre_save, post_save, or pre_delete occur.
Example:
python
CopyEdit
from django.db.models.signals import pre_save
from django.dispatch import receiver
@receiver(pre_save, sender=Book)
def modify_title(sender, instance, **kwargs):
instance.title = instance.title.upper()
Answer: You can delete a model instance using the delete() method. This will remove
the record from the database.
Example:
python
CopyEdit
book = Book.objects.get(id=1)
book.delete() # Deletes the book record from the database
Answer: A ModelForm is a class that provides a way to create a form directly from a
model. It automatically generates form fields based on the model's fields, which can be
used for creating or updating model instances via forms.
Example:
python
CopyEdit
from django import forms
from .models import Book
class BookForm(forms.ModelForm):
class Meta:
model = Book
fields = ['title', 'author', 'published_date']
Answer: Meta options in Django models are used to configure various properties of the
model such as ordering, indexes, verbose name, and database table name.
Example:
python
CopyEdit
class Book(models.Model):
title = models.CharField(max_length=100)
class Meta:
ordering = ['title']
db_table = 'book_table'
Answer: You can add a unique constraint to a field by setting the unique=True option in
the model field definition. Django ensures that no two records can have the same value
for the unique field.
Example:
python
CopyEdit
class Book(models.Model):
title = models.CharField(max_length=100, unique=True)
Example:
python
CopyEdit
from django.db import transaction
with transaction.atomic():
book = Book.objects.create(title='New Book')
# Some other database operations
Answer: The db_column option is used to specify the name of the column in the
database that should be associated with the model field. This is useful when you want to
give the database column a different name than the model field.
Example:
python
CopyEdit
class Book(models.Model):
title = models.CharField(max_length=100, db_column='book_title')
Answer: The F() object in Django allows you to refer to model field values in queries,
and you can perform operations on them directly at the database level, which is more
efficient than fetching and updating objects in Python.
Example:
python
CopyEdit
from django.db.models import F
Book.objects.filter(id=1).update(price=F('price') + 5)
Answer:
Example:
python
CopyEdit
books = Book.objects.values('title', 'author')
books_list = Book.objects.values_list('title', 'author')
Answer: A QuerySet is a collection of database queries that Django ORM generates for
you. It represents a collection of objects from your database, which can be filtered,
sorted, and manipulated.
33. How can you handle database migrations when working in a team?
Answer: The flush() method resets the database by removing all data from all tables,
including resetting the primary key sequences. This is often used in test environments.
Example:
python
CopyEdit
from django.core.management import call_command
call_command('flush', verbosity=0, interactive=False)
35. What are constraints in Django models, and how are they applied?
Answer: Constraints in Django models are used to define rules on the database schema to
maintain data integrity. Constraints like unique, check, and foreign key can be added
to model fields. Django also supports UniqueConstraint and CheckConstraint for
enforcing rules at the database level.
Example:
python
CopyEdit
class Book(models.Model):
title = models.CharField(max_length=100)
class Meta:
constraints = [
models.UniqueConstraint(fields=['title'],
name='unique_title')
]
36. How can you limit the number of rows returned in a QuerySet in Django?
Answer: You can limit the number of rows returned by using methods like [:n] for
slicing or the limit() function in filter().
Example:
python
CopyEdit
books = Book.objects.all()[:5] # Limits to 5 rows
Answer: The db_table option allows you to specify the name of the table that the model
should use in the database. By default, Django uses the model’s class name as the table
name, but you can customize it with db_table.
Example:
python
CopyEdit
class Book(models.Model):
title = models.CharField(max_length=100)
class Meta:
db_table = 'custom_book_table'
Answer:
makemigrations: This command is used to create migration files based on the
changes made to models.
migrate: This command applies the migrations and updates the database schema
based on the migration files.