Unit 5: Models and Migrations and Django Admin - Subjective Questions
INT253 — Web Development In Python Using Django • Practice Questions with Detailed Answers
20 questions
Explain what a Django model is and describe how it represents data in a database.
Answer:
A Django model is a Python class that represents a database table. Each attribute of the class usually represents a database field, while each object created from the class represents a row in that table.
- Models are defined in the
models.pyfile of an application. - Django provides field classes such as
CharField,IntegerField,DateField,BooleanField, andTextField. - Django automatically creates an ORM layer that allows developers to work with database records using Python objects instead of writing SQL directly.
- By default, Django adds an auto-incrementing primary key field named
idif no primary key is explicitly defined. - Model metadata, such as ordering and table names, can be specified through the inner
Metaclass.
For example, a Student model may contain fields such as name, email, and enrollment date. Django uses this model to create and manipulate the corresponding database table.
Describe the important steps involved in creating a model in Django. Include a suitable example.
Answer:
The steps for creating a Django model are:
- Create or select a Django application within the project.
- Open the application's
models.pyfile. - Define a class that inherits from
django.db.models.Model. - Add fields using Django field classes.
- Specify options such as default values, uniqueness, nullability, and relationships when required.
- Run
python manage.py makemigrationsto generate migration files. - Run
python manage.py migrateto apply the model structure to the database.
Example:
from django.db import models
class Book(models.Model):
title = models.CharField(max_length=200)
author = models.CharField(max_length=100)
published_year = models.IntegerField()
available = models.BooleanField(default=True)
def __str__(self):
return self.titleHere, Django creates a database table for books with columns corresponding to the declared fields.
What are migrations in Django? Explain their purpose and describe the difference between makemigrations and migrate.
Answer:
Migrations are Django files that record changes made to models and allow those changes to be applied consistently to a database.
python manage.py makemigrationsexamines changes in model definitions and creates migration files.python manage.py migrateexecutes the migration files and changes the database schema.- Migrations can create tables, add or remove fields, alter field definitions, and create relationships.
- They provide a history of database schema changes and make it easier to share database updates with other developers.
- Migration files should generally be committed to version control.
The two commands have different roles. makemigrations prepares the schema change as Python migration instructions, while migrate applies those instructions to the configured database.
Explain the complete workflow for modifying an existing Django model and applying the changes to the database.
Answer:
When an existing model is modified, the following workflow should be followed:
- Edit the model in the application's
models.pyfile. - Add, remove, or modify fields and relationships as required.
- Run
python manage.py makemigrations app_nameto create a migration for the application. - Review the generated migration file to verify that the proposed changes are correct.
- Run
python manage.py migrateto apply the migration to the database. - Test the application, model queries, forms, and administrative interface.
- Commit both the model changes and migration files to version control.
If a new non-nullable field is added to a table containing existing rows, Django may request a default value or require the field to allow null values. This issue should be handled carefully because the selected default affects existing records.
Describe how the Django shell can be used to insert, retrieve, update, and delete model objects.
Answer:
The Django shell is started with:
python manage.py shellA model can then be imported and manipulated using Python statements.
-
Insert:
python
student = Student.objects.create(name="Asha", email="asha@example.com") -
Retrieve all records:
python
students = Student.objects.all() -
Retrieve one record:
python
student = Student.objects.get(id=1) -
Update:
python
student.email = "new@example.com"
student.save() -
Bulk update:
python
Student.objects.filter(active=False).update(active=True) -
Delete:
python
student.delete()
The shell is useful for testing models, checking data, verifying relationships, and experimenting with ORM queries before using them in views.
Compare get(), filter(), all(), and exclude() methods in the Django ORM.
Answer:
These methods are used to retrieve model objects, but they behave differently.
-
all()returns aQuerySetcontaining every object in the model table.
python
Book.objects.all() -
filter()returns aQuerySetcontaining objects that satisfy the specified conditions.
python
Book.objects.filter(available=True) -
exclude()returns aQuerySetcontaining objects that do not satisfy the specified conditions.
python
Book.objects.exclude(published_year__lt=2000) -
get()returns exactly one object. It raisesDoesNotExistif no object matches andMultipleObjectsReturnedif more than one object matches.
python
Book.objects.get(id=1)
filter(), exclude(), and all() return query sets, which can be chained and evaluated lazily. get() is intended for a unique result.
Explain the concept of QuerySets in Django and discuss lazy evaluation with examples.
Answer:
A QuerySet is a collection of database queries represented by a Django ORM object. It can contain zero, one, or many model instances.
Django QuerySets are lazily evaluated. This means that creating or filtering a QuerySet does not immediately execute the database query. The query is normally executed when the results are needed, such as when:
- The QuerySet is iterated over.
- It is converted to a list.
- Its length is requested.
- It is printed or otherwise evaluated.
- Methods such as
exists()orfirst()are called.
Example:
books = Book.objects.filter(available=True)
books = books.filter(published_year__gte=2020)The two filtering operations can be combined into one SQL query. This behavior improves efficiency because Django delays database access until the result is actually required.
Explain the main advantages of using Django's Object Relational Mapping system instead of writing SQL queries directly.
Answer:
Django's ORM maps Python classes and objects to database tables and rows. Its major advantages include:
- Productivity: Developers use Python methods instead of writing repetitive SQL.
- Database portability: The same model and query code can work with databases such as SQLite, PostgreSQL, and MySQL, subject to database-specific limitations.
- Security: ORM parameters are generally handled safely, reducing the risk of SQL injection when queries are written correctly.
- Maintainability: Model definitions provide a centralized description of data structure and relationships.
- Relationships: Foreign keys and related objects can be queried using Python syntax.
- Query composition: QuerySets can be filtered, ordered, sliced, and combined.
- Integration: The ORM works naturally with forms, views, migrations, and the Django admin.
Direct SQL is still useful for highly specialized or performance-critical queries, but the ORM is appropriate for most application operations.
What is a foreign key in Django? Explain how to define and use a model containing a foreign-key relationship.
Answer:
A foreign key represents a many-to-one relationship between two models. Many records in one model can be associated with one record in another model.
Example:
class Department(models.Model):
name = models.CharField(max_length=100)
class Employee(models.Model):
name = models.CharField(max_length=100)
department = models.ForeignKey(
Department,
on_delete=models.CASCADE,
related_name="employees"
)Here, many employees can belong to one department. The on_delete option specifies what happens to employees when their department is deleted. CASCADE deletes the related employees. Other options include PROTECT, SET_NULL, and SET_DEFAULT, depending on the desired behavior.
Objects can be created and accessed as follows:
department = Department.objects.get(id=1)
Employee.objects.create(name="Ravi", department=department)
department.employees.all()Distinguish between one-to-one, one-to-many, and many-to-many relationships in Django models.
Answer:
Django supports several common relationship types.
- One-to-one: One object in one model is related to exactly one object in another model. It is implemented using
OneToOneField. For example, one user may have one profile. - One-to-many: One object can be related to many objects, while each related object belongs to one parent. It is implemented using
ForeignKey. For example, one department can have many employees. - Many-to-many: Multiple objects on both sides can be related to multiple objects on the other side. It is implemented using
ManyToManyField. For example, students can enroll in many courses, and each course can contain many students.
Example declarations:
profile = models.OneToOneField(User, on_delete=models.CASCADE)
department = models.ForeignKey(Department, on_delete=models.CASCADE)
courses = models.ManyToManyField(Course)The relationship type should reflect the real-world data structure and determine how records are queried.
Explain how on_delete works with Django foreign keys. Compare CASCADE, PROTECT, SET_NULL, and SET_DEFAULT.
Answer:
The on_delete argument defines the behavior of related records when the referenced object is deleted.
CASCADE: Deletes dependent objects automatically. It is suitable when child records have no meaning without the parent.PROTECT: Prevents deletion of the referenced object if related records exist. Django raises a protection error.SET_NULL: Sets the foreign-key value toNULL. The field must be declared withnull=True.SET_DEFAULT: Replaces the foreign-key value with the field's default value. A valid default must be supplied.SET(value): Assigns a specified value or the result of a callable.DO_NOTHING: Performs no automatic action and may cause a database integrity error.
The choice depends on data ownership and business rules. For example, deleting an order should usually cascade to order items, while deleting an author may be prevented if books must be retained.
Describe the purpose of the Django admin interface and explain the steps for registering a model with it.
Answer:
The Django admin is a built-in, model-driven interface used by authorized users to manage application data. It supports creating, viewing, editing, and deleting records without requiring a custom user interface.
Steps to register a model:
- Create a superuser using
python manage.py createsuperuser. - Ensure
django.contrib.admin, authentication, sessions, and static files are configured inINSTALLED_APPSand middleware. - Open the application's
admin.pyfile. - Import the model.
- Register it with
admin.site.register().
Example:
from django.contrib import admin
from .models import Book
admin.site.register(Book)After starting the development server, the administrator can visit /admin/, log in, and manage the registered model.
Explain how ModelAdmin can be customized to make the Django admin interface more useful.
Answer:
A model's admin interface can be customized by creating a class that inherits from admin.ModelAdmin.
@admin.register(Book)
class BookAdmin(admin.ModelAdmin):
list_display = ("title", "author", "published_year", "available")
list_filter = ("available", "published_year")
search_fields = ("title", "author")
ordering = ("title",)Important options include:
list_displayspecifies columns shown in the object list.list_filteradds filtering controls.search_fieldsenables text searching.orderingcontrols the default sorting order.readonly_fieldsprevents selected fields from being edited.fieldsorfieldsetscontrols form layout.list_editablepermits selected fields to be edited directly in the list.
Customization improves data management, reduces navigation time, and helps administrators locate records efficiently.
Explain how groups and users are added and managed in Django.
Answer:
Django includes a built-in authentication framework containing users, groups, permissions, password hashing, login support, and session handling.
Users can be managed through the admin interface or created programmatically:
from django.contrib.auth.models import User
user = User.objects.create_user(
username="meena",
email="meena@example.com",
password="strong-password"
)A group is a collection of permissions that can be assigned to several users. Groups are created in the admin interface or through Python:
from django.contrib.auth.models import Group
group = Group.objects.create(name="Editors")
user.groups.add(group)Administrators can assign users to groups and manage permissions through the admin interface. Group membership allows permissions to be managed consistently for users with similar responsibilities.
Explain Django users and permissions. Distinguish between user permissions, group permissions, staff status, and superuser status.
Answer:
Django permissions control which actions a user can perform on application models. The default model permissions are usually add, change, delete, and view.
- User permissions: Permissions assigned directly to an individual user.
- Group permissions: Permissions assigned to a group; every member inherits them.
- Staff status: The
is_staffflag allows a user to access the admin site, but it does not automatically grant every permission. - Superuser status: The
is_superuserflag grants all permissions and should be limited to trusted administrators. - Active status: The
is_activeflag determines whether the account can generally be used for authentication.
Permissions can be checked in code using user.has_perm("app_label.codename"). Views can also use decorators or mixins to restrict access. Good permission design follows least privilege by granting only the access required for a user's role.
Describe Django's database configuration and explain the important options in the DATABASES setting.
Answer:
Django database configuration is defined in the project's settings.py file under the DATABASES dictionary.
Example for SQLite:
DATABASES = {
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": BASE_DIR / "db.sqlite3",
}
}Important options include:
ENGINE: Identifies the database backend, such as SQLite, PostgreSQL, or MySQL.NAME: Specifies the database name or SQLite file path.USER: Database username for server-based databases.PASSWORD: Database password.HOST: Database server address.PORT: Database server port.OPTIONS: Additional backend-specific connection settings.
After configuring the database, the connection should be tested by running migrations and checking whether Django can create and retrieve model data.
Compare SQLite, PostgreSQL, and MySQL as database choices for a Django application.
Answer:
The three databases differ in their typical use cases.
- SQLite:
- File-based and requires minimal setup.
- Suitable for learning, prototypes, tests, and small applications.
- Has limitations for high concurrency and large production workloads.
- PostgreSQL:
- Feature-rich open-source relational database.
- Supports strong integrity, advanced queries, indexing, and concurrent workloads.
- Commonly selected for production Django applications.
- MySQL:
- Widely used relational database with good performance and production support.
- Requires a server configuration and careful attention to engine and compatibility settings.
The database backend is selected through the ENGINE setting. Although Django's ORM provides portability, developers should test database-specific behavior, transactions, indexes, constraints, and deployment settings before changing database systems.
Explain the process of configuring a PostgreSQL database connection for Django.
Answer:
The general process is:
- Install and start PostgreSQL.
- Create a database and a database user.
- Grant the required privileges to that user.
- Install a PostgreSQL driver, such as
psycopg. - Update the Django
DATABASESsetting. - Run
python manage.py migrateto create Django's tables. - Start the server and verify that the application can access the database.
Example configuration:
DATABASES = {
"default": {
"ENGINE": "django.db.backends.postgresql",
"NAME": "school_db",
"USER": "school_user",
"PASSWORD": "database-password",
"HOST": "localhost",
"PORT": "5432",
}
}In production, credentials should be supplied through environment variables or a secret-management system rather than being hard-coded in source files.
Explain how a Django model is converted into database tables through migrations.
Answer:
Django converts model definitions into database schema operations through the migration framework.
- A model class describes the required table and fields.
makemigrationscompares the current model state with the state recorded in previous migrations.- It creates migration operations such as
CreateModel,AddField,AlterField, orDeleteModel. migratereads these operations and asks the database backend to execute the corresponding SQL.- Django records applied migrations in the
django_migrationstable. - The exact SQL may vary between database backends, but the model-level migration remains portable in most cases.
For example, adding an email field may produce an AddField operation. Django then modifies the corresponding database table when the migration is applied.
Explain how to perform update and delete operations using Django ORM QuerySets. Mention important precautions.
Answer:
Django supports both object-level and bulk operations.
For an object-level update:
book = Book.objects.get(id=1)
book.available = False
book.save()For a bulk update:
Book.objects.filter(published_year__lt=2000).update(available=False)For deletion:
book = Book.objects.get(id=1)
book.delete()A bulk deletion can be performed with:
Book.objects.filter(available=False).delete()Important precautions are:
- Verify the filter condition before updating or deleting.
- Use transactions for related multi-step changes.
- Understand cascading behavior caused by foreign keys.
- Remember that bulk
update()does not call each object'ssave()method. - Avoid deleting records permanently when archival or soft deletion is required.
Explain what a Django model is and describe how it represents data in a database.
Answer:
A Django model is a Python class that represents a database table. Each attribute of the class usually represents a database field, while each object created from the class represents a row in that table.
- Models are defined in the
models.pyfile of an application. - Django provides field classes such as
CharField,IntegerField,DateField,BooleanField, andTextField. - Django automatically creates an ORM layer that allows developers to work with database records using Python objects instead of writing SQL directly.
- By default, Django adds an auto-incrementing primary key field named
idif no primary key is explicitly defined. - Model metadata, such as ordering and table names, can be specified through the inner
Metaclass.
For example, a Student model may contain fields such as name, email, and enrollment date. Django uses this model to create and manipulate the corresponding database table.
Did this save you a night before the exam?
LPU Notes is free, and it stays free. Ads cover part of the server bill. The rest comes out of a student's own pocket: the domain, the storage, and keeping the site up through the weeks everyone needs it at once.
The payment button didn't load. An ad blocker or a filtered network is the usual reason. to try again.
Nothing here is ever locked, and nothing unlocks. Chip in only if it was worth it. What it pays for →