Django Fastapi Questions

Software Engineer | 46 questions | 2026

Django and FastAPI Interview Questions and Answers

ORM, DRF, middleware, Pydantic, async endpoints. Tap a question to open the model answer, most asked first.

Django and FastAPI interview questions for freshers 20

Q1FresherMost asked
Answer

Explain the Django MVT architecture. How is it different from MVC?

Django uses Model, View, Template (MVT).

  • Model: Python classes that define data and map to database tables through the ORM.
  • View: a function or class that receives an HTTP request, talks to models, and returns a response. This is the logic, similar to a controller in MVC.
  • Template: the HTML presentation layer with Django template language.

The "controller" role in MVC is played by the framework itself: the URL dispatcher (urls.py) routes a request to the right view.

# urls.py
path("posts/", views.post_list)

# views.py
def post_list(request):
    posts = Post.objects.order_by("-created")[:10]
    return render(request, "posts.html", {"posts": posts})

So MVT is MVC with different names: Django's view is MVC's controller and Django's template is MVC's view. In a REST API setup, templates are replaced by serializers returning JSON.

What they are checking: Whether you can map Django's terms to MVC without confusion

Q2FresherMost asked
Answer

What is Django ORM? Show basic create, read, update and delete operations.

The ORM (Object Relational Mapper) lets you use database rows as Python objects. It writes the SQL for you. Each model class maps to a table and each field to a column.

class Book(models.Model):
    title = models.CharField(max_length=200)
    price = models.DecimalField(max_digits=8, decimal_places=2)
    author = models.ForeignKey("Author", on_delete=models.CASCADE)

b = Book.objects.create(title="Dune", price=9.99, author=a)    # create
Book.objects.filter(price__lt=10).order_by("title")            # read
Book.objects.filter(id=b.id).update(price=12)                  # update
b.delete()                                                     # delete

Benefits: it works with many databases, it escapes values to stop SQL injection, and it has migrations. Limits: complex report queries may need .raw() or raw SQL. Careless use makes slow queries (see N+1).

What they are checking: Comfort with the ORM and awareness of its limits

Q3FresherMost asked
Answer

What is the difference between `select_related` and `prefetch_related`?

Both avoid extra queries when you access related objects, but they work differently.

select_relatedprefetch_related
RelationsForeignKey, OneToOne (single-valued)ManyToMany, reverse FK, generic relations
HowSQL JOIN, one queryOne extra query per relation, joined in Python
ResultRelated objects come in the same rowSaved on each object from an IN (...) query
# one query with JOIN
books = Book.objects.select_related("author")

# two queries: books, then authors' tags
authors = Author.objects.prefetch_related("books")

# fine-tune the prefetch
from django.db.models import Prefetch
Author.objects.prefetch_related(
    Prefetch("books", queryset=Book.objects.filter(published=True))
)

Use select_related for "one" side joins and prefetch_related for "many" side. Check with django-debug-toolbar or len(connection.queries).

What they are checking: The join versus second-query distinction

Q4FresherMost asked
Answer

What are Django migrations and how do they work?

Migrations are Python files, kept in version control, that describe changes to your database schema (create model, add field, change field). Django creates them from your model changes.

python manage.py makemigrations     # detect model changes, write migration files
python manage.py migrate            # apply unapplied migrations
python manage.py showmigrations     # list applied state
python manage.py sqlmigrate app 0003  # preview SQL
  • Applied migrations are recorded in the django_migrations table.
  • Each migration lists its dependencies, so they form a graph.
  • Migrations can also change data with RunPython and run raw SQL with RunSQL.
  • Commit migration files to git. Never edit an applied one; create a new migration.
  • If two branches create the same migration number, fix it with makemigrations --merge.

What they are checking: Practical workflow and not editing applied migrations

Q5FresherMost asked
Answer

What is the difference between Django, Flask and FastAPI? When would you choose each?

DjangoFlaskFastAPI
StyleEverything included, full-stackSmall framework, you add the piecesModern async API framework
Built-inORM, admin, auth, forms, migrationsRouting, templating (Jinja)Routing, validation, OpenAPI docs
ProtocolWSGI, ASGI supportedWSGI (async limited)ASGI, async first
ValidationForms, DRF serializersExtensionsPydantic from type hints
Best forContent sites, admin-heavy apps, single big appsSmall services, prototypesHigh-performance JSON APIs, microservices

Choose Django when you want a complete, convention-driven stack and an admin panel quickly. Choose Flask for small, flexible apps where you pick every library. Choose FastAPI for API-only services where automatic docs, type-driven validation and async I/O matter. They can coexist: a Django monolith plus FastAPI microservices is common.

What they are checking: Reasons for each choice, not just a favourite

Q6FresherMost asked
Answer

What is a serializer in Django REST Framework? How do `Serializer` and `ModelSerializer` differ?

A serializer turns complex objects (model instances, querysets) into plain Python types for JSON output. It also checks incoming data and turns it back into objects.

  • Serializer: you declare every field and implement create/update yourself.
  • ModelSerializer: makes the fields and default create and update from a model.
class BookSerializer(serializers.ModelSerializer):
    author_name = serializers.CharField(source="author.name", read_only=True)

    class Meta:
        model = Book
        fields = ["id", "title", "price", "author", "author_name"]

    def validate_price(self, value):
        if value <= 0:
            raise serializers.ValidationError("must be positive")
        return value

Use validate_<field> for single-field rules and validate() for cross-field rules. Call serializer.is_valid(raise_exception=True) then serializer.save(). Avoid fields = "__all__" in public APIs, because new model fields would be shown automatically.

What they are checking: Validation hooks and controlling what is shown

Q7FresherMost asked
Answer

What is Pydantic and how does FastAPI use it?

Pydantic is a data validation library that uses Python type hints. You define a model. It reads and checks the input, changes types where it makes sense, and gives clear errors. FastAPI uses Pydantic models for request bodies and responses, and to build the OpenAPI schema.

from fastapi import FastAPI
from pydantic import BaseModel, Field, EmailStr

class UserIn(BaseModel):
    name: str = Field(min_length=2)
    age: int = Field(ge=0, le=120)
    email: EmailStr          # requires email-validator package

class UserOut(BaseModel):
    id: int
    name: str

app = FastAPI()

@app.post("/users", response_model=UserOut, status_code=201)
def create(user: UserIn):
    return {"id": 1, "name": user.name}

Invalid input returns an automatic 422 with details. response_model removes fields like passwords. Pydantic v2 (written in Rust) is much faster than v1 and uses model_validate, model_dump, and field_validator.

What they are checking: Validation and response filtering in FastAPI

Q8FresherMost askedFree with sign-in
Answer

Are Django QuerySets lazy? Explain when the database is actually hit.

Yes. Building or chaining a QuerySet does not run SQL. The query runs only when the results are needed.

Q9FresherMost askedFree with sign-in
Answer

Explain model relationships in Django: ForeignKey, OneToOne and ManyToMany.

  • ForeignKey: many-to-one. Many books belong to one author.
  • OneToOneField: one-to-one, e.g. a Profile extending a user.
  • ManyToManyField: many-to-many, e.g. students and courses. Django creates a hidden join table, or you define a through model to store extra fields.
Q10FresherMost askedFree with sign-in
Answer

How do path parameters, query parameters and request bodies work in FastAPI?

FastAPI decides by where the parameter appears and by its type.

  • In the path string: path parameter.
  • Simple types not in the path: query parameter.
  • A Pydantic model: JSON request body.
Q11FresherMost askedFree with sign-in
Answer

Describe the request-response lifecycle in Django.

  1. The web server (through WSGI or ASGI) gives the request to Django, which builds an HttpRequest.
  2. Request middleware runs in the order listed in MIDDLEWARE (security, sessions, CSRF, authentication).
  3. The URL resolver matches the path against urlpatterns and picks a view.
  4. The view runs. It may query the...
Q12FresherMost askedFree with sign-in
Answer

What is middleware in Django? How do you write a custom one?

Middleware is a chain of hooks. They process every request before the view and every response after it. Built-ins handle security headers, sessions, CSRF protection and authentication.

Q13FresherMost askedFree with sign-in
Answer

What is the difference between authentication and authorization (permissions) in DRF?

Authentication finds out who the caller is. Authorization decides what they may do. In DRF they are separate parts.

  • authentication_classes set request.user and request.auth. Failure gives 401.
  • permission_classes check access. Failure gives 403.
Q14FresherMost askedFree with sign-in
Answer

How does CSRF protection work in Django?

CSRF (Cross-Site Request Forgery) tricks a logged-in user's browser into sending a request the user did not want. Django stops this with a secret token that a bad site cannot read.

Q15FresherMost askedFree with sign-in
Answer

What is the difference between `get()` and `filter()` in Django ORM?

get() returns exactly one object, and raises an error if there are none or many. filter() returns a QuerySet (it may be empty) and never raises an error for no results.

Q16FresherMost askedFree with sign-in
Answer

How do you manage settings and secrets for multiple environments in Django?

Keep configuration out of the code and read it from environment variables. Use one settings module per environment, or one module that reads env vars.

Q17FresherMost askedFree with sign-in
Answer

What is FastAPI's automatic documentation and how is it generated?

FastAPI builds an OpenAPI schema from your routes, type hints and Pydantic models. It serves interactive docs with no extra work.

  • Swagger UI at /docs, where you can try requests.
  • ReDoc at /redoc.
  • Raw schema at /openapi.json.
Q18FresherMost askedFree with sign-in
Answer

What built-in security features does Django provide and what settings should you check before going live?

Django protects against several common attacks by default:

Q19FresherMost askedFree with sign-in
Answer

How are static files and media files handled in Django?

Static files are assets that come with the code (CSS, JS, images). Media files are uploads from users.

Q20FresherMost askedFree with sign-in
Answer

What are Django admin and ModelAdmin? How would you customise it?

The Django admin is a back-office website that Django makes for you. It manages model data and comes from django.contrib.admin. You register models and change the screen with a ModelAdmin.

Django and FastAPI interview questions for experienced 17

Q21ExperiencedMost asked
Answer

What is the N+1 query problem in Django and how do you fix it?

N+1 happens when you run one query to get N objects. Then you run one more query for each object to get a related row. That gives N+1 queries.

# 1 query for books + 1 query per book for author
for book in Book.objects.all():
    print(book.author.name)

Fixes:

  • select_related("author") for ForeignKey or OneToOne (JOIN).
  • prefetch_related("tags") for many-valued relations.
  • .only() / .values() to fetch only the columns you need.
  • Count in SQL (annotate(n=Count("comments"))) instead of counting in a loop.

Find it with django-debug-toolbar, assertNumQueries in tests, or the django.db.backends logger. In DRF, the serializer is the usual cause: put the select_related/prefetch_related in the viewset's get_queryset.

What they are checking: Recognising the pattern and tools to detect it

Q22ExperiencedMost asked
Answer

How does authentication work in Django and DRF? Compare session, token and JWT authentication.

Django's own auth uses sessions. Login stores a session id in a cookie, and the server looks up the user on each request. DRF adds authentication classes you can swap in, and they set request.user.

SessionToken (DRF TokenAuthentication)JWT (e.g. SimpleJWT)
StateServer stores sessionServer stores token in DBStateless signed token
TransportCookie (needs CSRF)Authorization: Token ...Authorization: Bearer ...
RevocationDelete sessionDelete tokenHard, needs short expiry plus a blocklist
Best forBrowser apps on same domainSimple clientsMobile/SPA, microservices

JWT practice: use a short-lived access token (a few minutes) and a refresh token to renew it. Sign with a strong secret or key pair. Always use HTTPS. If XSS is a worry, keep tokens out of localStorage (HttpOnly cookies are safer). Authentication says who you are. Permissions decide what you may do.

What they are checking: Pros and cons of stateful and stateless auth

Q23ExperiencedMost askedFree with sign-in
Answer

Explain dependency injection in FastAPI with an example.

FastAPI's Depends lets you write reusable pieces (database session, current user, settings, pagination) as functions. FastAPI calls them and passes the results into your endpoint.

Q24ExperiencedMost askedFree with sign-in
Answer

What is the difference between `def` and `async def` endpoints in FastAPI?

FastAPI supports both. async def endpoints run directly on the event loop. Plain def endpoints run in a pool of worker threads, so they do not block it.

Q25ExperiencedMost askedFree with sign-in
Answer

How do you deploy a Django or FastAPI app to production with gunicorn and uvicorn?

Run the app server behind a reverse proxy (Nginx or a cloud load balancer). Manage it with systemd or containers.

  • Django (WSGI): gunicorn project.wsgi:application --workers 4 --bind 0.0.0.0:8000.
  • Django or FastAPI (ASGI): gunicorn as process manager with uvicorn workers:
Q26ExperiencedMost askedFree with sign-in
Answer

What are Django signals? When should you avoid them?

Signals tell one part of the app when something happens in another part (the observer pattern). Common ones: pre_save, post_save, post_delete, m2m_changed, request_finished.

Q27ExperiencedMost askedFree with sign-in
Answer

What are APIView, generic views and ViewSets in DRF? When do you use each?

Each one does more for you than the last.

Q28ExperiencedMost askedFree with sign-in
Answer

How do you run background tasks? Compare FastAPI BackgroundTasks with Celery.

FastAPI's BackgroundTasks runs a function after the response is sent, in the same process.

Q29ExperiencedMost askedFree with sign-in
Answer

How do database transactions work in Django? What does `atomic` do?

By default, Django uses autocommit mode, so each query is its own transaction. transaction.atomic groups operations so they all save or all roll back.

Q30ExperiencedMost askedFree with sign-in
Answer

How do you use Celery with Django? What problems does it solve?

Celery is a task queue that runs on many machines. The web process puts a message on a broker (Redis or RabbitMQ). Separate worker processes run it. So long or unreliable work runs outside the request.

Q31ExperiencedMost askedFree with sign-in
Answer

What caching options does Django provide and how do you use them?

Django has a cache framework with several backends: local memory, file, database, Memcached and Redis (the usual choice in production).

Q32ExperiencedMost askedFree with sign-in
Answer

How do you handle pagination, filtering and throttling in DRF?

All three can be set in settings or per view.

Q33ExperiencedMost askedFree with sign-in
Answer

How do you connect FastAPI to a database with SQLAlchemy and manage sessions?

Create the engine and session factory once. Give each request its own session through a dependency that closes it afterwards.

Q34ExperiencedMost askedFree with sign-in
Answer

What is the difference between WSGI and ASGI?

Both are rules for how a Python web server talks to a web application.

Q35ExperiencedMost askedFree with sign-in
Answer

How do you test a Django app and a FastAPI app?

Use pytest with the framework's test client, a test database and fixtures.

Django:

Q36ExperiencedMost askedFree with sign-in
Answer

Why should you create a custom user model at the start of a Django project?

Django's default User is hard to change later. Other tables point to it with foreign keys, and migrations depend on it. Setting AUTH_USER_MODEL before the first migration lets you add fields (phone, role) or log in with email.

Q37ExperiencedMost askedFree with sign-in
Answer

What is a custom through table in a Django ManyToMany relationship, and when do you need one?

A custom through model is a join table you define yourself for a ManyToManyField. It lets you store extra data about the link, such as when a student joined a course.

Scenario based Django and FastAPI interview questions 9

Q38ExperiencedMost askedScenario
Answer

An API list endpoint makes about 500 database queries and takes 4 seconds. How do you diagnose and fix it?

Measure first. Then remove the repeated queries.

  1. Count queries with django-debug-toolbar or django-silk locally, or enable the django.db.backends logger. Tests can pin the number with self.assertNumQueries(3).
  2. If the query count grows with the number of rows, it is N+1. Find the field that the serializer or template reads, which causes one query per object.
  3. Fix in get_queryset: select_related for FKs, prefetch_related (with Prefetch objects for filtered relations) for reverse and M2M, and annotations for counts and sums.
  4. Send less data: only()/defer(), paginate (PageNumberPagination or cursor pagination), avoid big nested objects.
  5. Look at slow SQL with EXPLAIN ANALYZE and add indexes (db_index=True, Meta.indexes) on filtered and ordered columns.
  6. If it is still slow, cache the result in Redis and measure again.

Goal: a small, fixed number of queries, no matter how many rows. Add a test to keep it that way.

What they are checking: Methodical diagnosis with ORM-level tooling

Q39ExperiencedMost askedScenarioFree with sign-in
Answer

A Django or FastAPI endpoint is slow only under load. How do you find the cause?

A slowdown that only appears with many users usually means requests are fighting for a limited resource.

Q40ExperiencedMost askedScenarioFree with sign-in
Answer

How would you scale a Django or FastAPI application to handle 10 times more traffic?

Scale in steps. Start with the cheapest wins.

Q41ExperiencedMost askedScenarioFree with sign-in
Answer

Two users try to book the last seat at the same moment and both succeed. How do you prevent double booking?

This is a race condition: the code reads first and writes later. Make the check and the update happen as one step in the database.

Option 1: lock the row.

Q42ExperiencedMost askedScenarioFree with sign-in
Answer

The app works locally but returns 500 errors only in production. How do you debug it?

Start with facts, not guesses.

Q43ExperiencedMost askedScenarioFree with sign-in
Answer

Which would you pick for a new project: Django with DRF or FastAPI? Walk through your decision.

Decide by needs, team and tools, not by hype.

Pick Django + DRF when:

  • You need an admin panel, auth, ORM and migrations ready to use.
  • The product is one big app built around a database, or has pages made on the server.
  • The team knows Django, and you want proven conventions and many ready packages.
Q44ExperiencedMost askedScenarioFree with sign-in
Answer

A user signs up and the endpoint takes 6 seconds, because it sends an email and calls an outside API. How do you fix this?

Keep only the essential work in the request. Move the slow parts out of it.

Q45ExperiencedMost askedScenarioFree with sign-in
Answer

How do you add a column to a table with 50 million rows in production without downtime?

Avoid long locks. Make sure old code and new code both work during the rollout (add first, remove later).

Q46ExperiencedMost askedScenarioFree with sign-in
Answer

How would you secure a public REST API built with Django or FastAPI against abuse?

Use many layers of defence.

Test yourself on DjangoQuick MCQs, right or wrong shown instantlyStart

More Software Engineer interview questions