Django Interview Questions 1-5 (MVT, Core Features, Flask, ORM)
Welcome! We're now moving from general Python and database theory to one of the most popular and powerful web frameworks in the ecosystem: Django. As a full-stack developer, this is where your Python skills and your database knowledge come together to build real applications.
This lesson covers the absolute fundamentals of "thinking in Django." We'll look at its core architecture (MVT), what makes it so powerful, how it compares to its main alternative (Flask), and its most famous feature: the Object-Relational Mapper (ORM).
1. Explain Django’s MVT architecture.
Django follows a Model-View-Template (MVT) architecture. This is a design pattern that separates the application's logic into three distinct parts, which makes your code much cleaner, more organized, and easier to maintain.
It's very similar to the more common Model-View-Controller (MVC) pattern, but Django handles the "Controller" part differently.
Analogy: A Restaurant
Imagine you are at a restaurant:
- Model (The Kitchen / Database):
This is the data layer. The Model defines the structure of your data and how to interact with it. It is the single, definitive source of truth.
Restaurant: This is the kitchen and the pantry. It has the raw ingredients (`data`) and the rules about what can be made (`schema`). A Django `models.py` file is the blueprint for your database tables. - View (The Chef / Business Logic):
This is the business logic layer. The View takes a request from the user, goes to the Model (kitchen) to get the data (ingredients), does some work on it (cooks the food), and then decides what to send back.
Restaurant: This is the chef. The waiter gives the chef an order. The chef gets ingredients from the kitchen (`Model`), prepares the dish (`business logic`), and hands the finished plate to the waiter. - Template (The Menu / Presentation):
This is the presentation layer. It's the HTML file (with some special Django tags) that defines the structure of the final page. The View (chef) hands data to the Template, which renders it for the user to see.
Restaurant: This is the menu you read from, or the final plated dish. It's how the data is presented to you. The chef (`View`) decides what data to include, but the `Template` defines how it looks.
In Django, the "Controller" part (the waiter who routes your order) is handled by the framework itself via the `urls.py` file.
2. What are the main features of Django?
Django is often called a "batteries-included" framework. This means it comes with almost everything you need to build a complex, secure, and scalable web application right out of the box.
- The ORM (Object-Relational Mapper): This is its most famous feature. It lets you interact with your database using simple Python code instead of writing raw SQL. (We'll cover this next).
- The Admin Site: Django automatically builds a powerful and secure admin website based on your models. You can create, edit, and delete data without writing any extra code.
- Security (Out of the Box): Django comes with built-in protection against the most common web attacks, such as SQL Injection (via the ORM), Cross-Site Scripting (XSS) (via the template engine), and CSRF (Cross-Site Request Forgery).
- Authentication & Authorization: It has a complete system for handling user accounts, login, logout, password resets, and permissions (e.g., "is_staff", "is_superuser").
- Migrations System: This is a huge advantage. When you change your `models.py` (e.g., add a new column), Django automatically generates the SQL script needed to safely update your database schema without losing data.
3. Difference between Django and Flask.
This is the most common framework comparison. Both are excellent, but they have fundamentally different philosophies.
Analogy: Building a House
- Django (The All-Inclusive Kit):
Django is like buying a high-end, prefabricated house kit. It comes with the foundation, walls, plumbing, electricity, and security system (ORM, Admin, Auth, Security) all included and designed to work together.
- Pros: Incredibly fast to get started on a complex app. Very secure. Follows a strict, clear project structure.
- Cons: Opinionated. If you don't like its way of doing things (e.g., you want to use a different ORM), it can be difficult. It's a "heavy" framework for a small project. - Flask (The Toolbox):
Flask is a "micro-framework." It's like buying a high-quality toolbox that contains a hammer (routing), a screwdriver (template engine), and a measuring tape (testing).
- Pros: Extremely lightweight, flexible, and simple to start. You have total control. You can hand-pick every tool you want (e.g., you choose your ORM, your admin panel, etc.).
- Cons: For a complex app, you are responsible for building or finding all the parts (auth, admin, etc.) and making them work together.
Summary:
- Choose Django for large, data-driven applications where you need an admin panel and a database out of the box (e.g., e-commerce, CMS, blogs).
- Choose Flask for small microservices, simple APIs, or projects where you want full control and flexibility.
4. Explain Django ORM and its advantages.
The ORM (Object-Relational Mapper) is a powerful feature that lets you interact with your database using Python objects instead of writing raw SQL.
You define your database table as a Python `class` (the Model). The ORM is the translatorthat converts your Python commands into complex SQL queries.
Analogy: The Translator
Imagine you (a Python developer) need to talk to a database (a SQL-speaking accountant).
- Without ORM: You must learn fluent SQL. You write a detailed, complex memo in SQL: `SELECT name, email FROM users WHERE age > 30...`
- With ORM: You just speak Python to the ORM (your translator): `User.objects.filter(age__gt=30)`. The translator instantly writes the perfect, optimized SQL memo for you.
Advantages:
- Productivity: It's much faster to write `User.objects.get(pk=1)` than `SELECT * FROM users WHERE user_id = 1;`.
- Security: The ORM automatically parameterizes all queries, which prevents SQL injection attacks.
- Database Agnostic: You write your code in Python. If you switch your database from SQLite to PostgreSQL, you don't have to change your query code at all. The ORM handles the different SQL dialects.
- Readability: It's just Python. It's easier for other developers to read and maintain.
5. Difference between ORM and raw SQL in Django.
This is a practical follow-up. While the ORM is amazing, sometimes you need to break out of it and write raw SQL.
Here is a direct comparison of the two approaches, showing how to get the exact same result.
# First, assume we have this Django model:
#
# class User(models.Model):
# name = models.CharField(max_length=100)
# age = models.IntegerField()
# is_active = models.BooleanField(default=True)
# --------------------------------------------------
# GOAL: Get the names of all active users over 30
# --------------------------------------------------
# --- Method 1: The Django ORM ---
# This is Pythonic, clean, and 100% secure
# from SQL injection.
users = User.objects.filter(
age__gt=30,
is_active=True
).values_list('name', flat=True)
# The ORM translates this into a SQL query
# that looks something like this:
# "SELECT name FROM app_user WHERE age > 30 AND is_active = 1"
# --- Method 2: Raw SQL ---
# We write the SQL by hand.
# Note: We MUST parameterize to prevent SQL injection.
from django.db import connection
query = """
SELECT name FROM app_user
WHERE age > %s AND is_active = %s
"""
params = [30, True]
with connection.cursor() as cursor:
cursor.execute(query, params)
# .fetchall() returns a list of tuples, e.g., [('Alice',), ('Bob',)]
rows = cursor.fetchall()
# We have to manually flatten the list
users_raw = [row[0] for row in rows]
| Feature | Django ORM | Raw SQL |
|---|---|---|
| Usage | Use for 95% of queries. | Use for highly complex queries, or when performance is critical. |
| Security | Secure by default. | You are responsible for security (parameterization). |
| Readability | Excellent. It's just Python. | Can be complex. Mixes SQL strings in Python code. |
| Portability | Works on PostgreSQL, MySQL, SQLite, etc. | Query may be database-specific (e.g., using `LIMIT` vs. `TOP 1`). |
| Performance | Very good, but can be non-optimal for complex `JOIN`s. | Can be faster if you are a SQL expert and can hand-tune the query. |