Django Interview Questions and Answers


What is Django?
  • Django is a high-level Python Web framework that encourages rapid development and clean, pragmatic design. It follows the "batteries included" philosophy, providing many built-in features.
What architectural pattern does Django follow?
  • Django follows the Model-Template-View (MTV) architectural pattern, which is a variation of the Model-View-Controller (MVC) pattern.
Explain the components of the MTV pattern in Django.
  • Model: Represents the data structure (database tables) and handles data interactions.
  • Template: Defines the presentation logic and structures the HTML output.
  • View: Acts as the intermediary, receiving requests, interacting with the Model, selecting the appropriate Template, and returning a response.
What is the difference between Django's MTV and the traditional MVC?
  • In traditional MVC:
    • Model: Data and business logic.
    • View: User interface.
    • Controller: Handles user input, interacts with Model and View.
  • In Django's MTV:
    • Model: Data structure and database interactions.
    • Template: User interface presentation.
    • View: Handles the request, interacts with Model, selects Template, and prepares the response (acts more like the Controller).
What are the key features of Django?
  • ORM (Object-Relational Mapper).
  • Built-in Admin Panel.
  • URL Dispatcher.
  • Templating Engine.
  • Forms handling.
  • Authentication and Authorization system.
  • Caching framework.
  • Security features (CSRF protection, XSS protection, SQL injection protection).
  • Internationalization and Localization support.
What is an app in Django?
  • An app is a self-contained module within a Django project that provides specific functionality (e.g., a blog app, a user management app). A project can consist of multiple apps.
What is a project in Django?
  • A project is a collection of settings and apps that together constitute a complete web application.
How do you create a new Django project?
  • Using the command: django-admin startproject project_name.
How do you create a new Django app?
  • Navigate to the project's root directory (where manage.py is) and use the command: python manage.py startapp app_name.
What is the purpose of manage.py?
  • manage.py is a command-line utility that lets you interact with your Django project. It provides various commands for database migrations, running the development server, creating apps, etc.
What are Django Models?
  • Models are Python classes that define the structure of your data. They map to database tables and provide an interface for interacting with the database through Django's ORM.
How do you define a Model in Django?
  • By creating a Python class that subclasses django.db.models.Model and defining model fields as class attributes.
What are some common Model Field types?
  • CharField, TextField, IntegerField, FloatField, BooleanField, DateField, DateTimeField, EmailField, URLField, ImageField, FileField, ForeignKey, ManyToManyField, OneToOneField.
Explain the different types of Model Relationships.
  • ForeignKey: A many-to-one relationship. One record in the current model relates to one record in another model (e.g., many "Comments" can belong to one "Post").
  • ManyToManyField: A many-to-many relationship. Records in the current model can relate to multiple records in another model, and vice versa (e.g., many "Articles" can have many "Tags").
  • OneToOneField: A one-to-one relationship. Each record in the current model relates to exactly one record in another model (e.g., a "User" might have one "Profile").
What are Migrations in Django?
  • Migrations are Django's way of propagating changes you make to your models (adding a field, deleting a model, etc.) into your database schema.
How do you create and apply Migrations?
  • Create migration files: python manage.py makemigrations.
  • Apply migrations to the database: python manage.py migrate.
What is the Django ORM?
  • The Object-Relational Mapper is a layer that allows you to interact with your database using Python objects and methods instead of writing raw SQL queries.
How do you fetch all objects from a Model using the ORM?
  • ModelName.objects.all().
How do you filter objects based on a condition?
  • ModelName.objects.filter(field_name=value) or using lookups like ModelName.objects.filter(field_name__gt=value).
How do you get a single object?
  • ModelName.objects.get(field_name=value). This raises an error if no object or multiple objects match.
How do you create a new object?
  • ModelName.objects.create(field1=value1, field2=value2, ...) or obj = ModelName(field1=value1, ...); obj.save().
How do you update an object?
  • Fetch the object, modify its attributes, and call .save(). Or use ModelName.objects.filter(...).update(field=new_value) for bulk updates.
How do you delete an object?
  • Fetch the object and call .delete(). Or use ModelName.objects.filter(...).delete() for bulk deletions.
What is a QuerySet?
  • A QuerySet represents a collection of objects from your database. QuerySets are lazy, meaning the database query is not executed until the QuerySet is evaluated (e.g., when iterating over it, slicing it, or calling methods like list(), len(), bool()).
What are Django Views?
  • Views are Python functions or classes that handle web requests, retrieve data from models, process it, and return a response, typically an HTML page rendered from a template, or other data formats like JSON.
What is the difference between Function-Based Views (FBVs) and Class-Based Views (CBVs)?
  • FBVs: Standard Python functions that take an HttpRequest object as input and return an HttpResponse object. Simpler for basic views.
  • CBVs: Python classes that inherit from base view classes. They provide more structure and allow for code reuse through inheritance and mixins. Better for complex views and leveraging Django's built-in generic views.
What is the purpose of the render() shortcut?
  • render() is a shortcut function that takes the HttpRequest object, a template name, and a context dictionary, and returns an HttpResponse object with the rendered template.
What is the purpose of the redirect() shortcut?
  • redirect() is a shortcut function that returns an HttpResponseRedirect object, which redirects the user to a different URL.
What are Django Templates?
  • Templates are text files (usually HTML) that contain static parts of the output plus special syntax (Django Template Language - DTL) describing how the dynamic content will be inserted.
Explain the Django Template Language (DTL).
  • DTL consists of:
    • Variables: Display values from the context ({{ variable }}).
    • Tags: Control logic (loops, conditionals, inheritance - {% tag %}).
    • Filters: Transform variable output ({{ variable|filter }}).
    • Comments: ({# comment #}).
What is Template Inheritance?
  • Template inheritance allows you to define a base template with common structure (like headers, footers, sidebars) and then have child templates override specific blocks of content. Uses the {% extends %} and {% block %} tags.
How do you include static files (CSS, JS, images) in Django templates?
  • Configure STATIC_URL and STATICFILES_DIRS in settings.py.
  • Use {% load static %} at the top of the template.
  • Use the {% static 'path/to/file' %} tag to generate the URL.
What is the Django URL Dispatcher?
  • The URL dispatcher maps URLs to views. It takes an incoming HTTP request and determines which view function or class should handle it based on the requested URL.
How do you define URLs in Django?
  • Using the path() or re_path() functions in urls.py files.
What is the purpose of the include() function in urls.py?
  • include() allows you to include URL patterns from other urls.py files (typically from Django apps) into the project's main URL configuration. This helps organize URLs.
What are named URLs?
  • Named URLs (using the name argument in path()) allow you to refer to URLs by a logical name instead of hardcoding the URL path. This makes your code more maintainable, as you can change the URL pattern without updating every link that points to it.
How do you generate a URL from a named URL in templates and Python code?
  • In templates: {% url 'name_of_url' arg1=value1 %}.
  • In Python: reverse('name_of_url', args=[value1]) or reverse_lazy().
What are Django Forms?
  • Django Forms provide a framework for handling HTML forms, validating user input, and rendering forms in templates.
What is the difference between a Form and a ModelForm?
  • Form: A general-purpose form that is not directly tied to a specific model. You define fields manually.
  • ModelForm: A form that is automatically generated based on a Django model. It simplifies creating forms for CRUD operations related to models.
How do you handle form submissions in a Django view?
  • Check if the request method is POST.
  • Instantiate the form with the POST data (form = MyForm(request.POST)).
  • Check if the form is valid (if form.is_valid():).
  • Access cleaned data (form.cleaned_data) or save the ModelForm (form.save()).
What is the Django Admin Panel?
  • The Django Admin Panel is an automatically generated administrative interface for your models. It provides a user-friendly way to manage your database content (create, read, update, delete).
How do you enable the Admin Panel?
  • Ensure the 'django.contrib.admin' app is in INSTALLED_APPS.
  • Include the admin URLs in your project's urls.py (path('admin/', admin.site.urls)).
  • Run python manage.py migrate to create the necessary tables.
How do you register your models with the Admin Panel?
  • Import the model in your app's admin.py and use admin.site.register(YourModel) or the @admin.register(YourModel) decorator.
How do you customize the appearance and behavior of models in the Admin Panel?
  • Create a class that subclasses admin.ModelAdmin, define customization options (like list_display, search_fields, list_filter), and register it with the model.
What is Django's Authentication System?
  • A built-in framework for handling user authentication (verifying a user's identity) and authorization (determining what a user is allowed to do).
How do you create a superuser?
  • python manage.py createsuperuser.
How do you require a user to be logged in to access a view?
  • For FBVs, use the @login_required decorator.
  • For CBVs, use the LoginRequiredMixin.
What are Django Signals?
  • Signals allow certain senders to notify a set of receivers that some action has taken place. They are useful for decoupling applications and allowing them to be notified of events without explicit coupling (e.g., sending an email after a user is created).
What is Django Middleware?
  • Middleware is a framework of hooks into Django's request/response processing. It's a lightweight plug-in system for globally altering Django's input or output (e.g., handling sessions, authentication, CSRF protection).
What are some common built-in middleware?
  • AuthenticationMiddleware, SessionMiddleware, CsrfViewMiddleware, SecurityMiddleware.
What is the purpose of settings.py?
  • settings.py is a Python module that contains the configuration for your Django project, including database settings, installed apps, template settings, static files settings, etc.
What is the difference between STATIC_URL and STATIC_ROOT?
  • STATIC_URL: The base URL for static files when served in development or by a production web server.
  • STATIC_ROOT: The absolute path to the directory where static files will be collected by the collectstatic command for deployment.
What is the purpose of the collectstatic command?
  • python manage.py collectstatic collects all static files from your apps and any specified directories into the STATIC_ROOT directory, making them ready for serving in production.
What is CSRF protection in Django?
  • CSRF (Cross-Site Request Forgery) protection is a security feature that helps prevent malicious websites from making unauthorized requests to your site on behalf of an authenticated user. Django's CsrfViewMiddleware and the {% csrf_token %} template tag handle this.
How do you include CSRF protection in your forms?
  • Include the {% csrf_token %} tag within the <form> tags in your template.
What is the purpose of the SECRET_KEY in settings.py?
  • SECRET_KEY is a secret string used for cryptographic signing in Django, including the creation of session keys and CSRF tokens. It should be kept confidential.
How do you handle file uploads in Django?
  • Use FileField or ImageField in your models.
  • Ensure the form's enctype is set to "multipart/form-data".
  • Access uploaded files via request.FILES in your view.
  • Configure MEDIA_ROOT and MEDIA_URL in settings.py for serving uploaded files.
What is the difference between STATIC_ and MEDIA_ settings?
  • STATIC_ settings are for static files that are part of your application's code (CSS, JS, images provided by the developer).
  • MEDIA_ settings are for user-uploaded files.
What are Django's built-in User and Group models?
  • Django provides a default User model for authentication and a Group model for assigning permissions to collections of users.
How can you customize the Django User model?
  • You can extend the built-in User model using a one-to-one relationship (using OneToOneField) or by creating a custom user model from scratch (subclassing AbstractUser or AbstractBaseUser) and specifying it with AUTH_USER_MODEL in settings.py.
What are Permissions in Django?
  • Permissions are flags that indicate whether a user or group is allowed to perform a specific action on a model (e.g., add, change, delete, view).
How do you check if a user has a specific permission?
  • Using the user.has_perm('app_label.permission_codename') method.
What is the purpose of the slug field?
  • A slug is a short label for something, containing only letters, numbers, underscores, or hyphens. They are typically used in URLs for human-readable identifiers (e.g., /blog/my-first-post/).
How do you handle pagination in Django?
  • Using Django's built-in Paginator class, typically in views.
What is the purpose of the get_absolute_url() method in a Model?
  • It's a convention to define a get_absolute_url() method on models that have a canonical URL. This method should return the absolute URL for an instance of that model. It's often used in the admin interface and by generic views.
What is the difference between reverse() and reverse_lazy()?
  • reverse(): Returns the URL string immediately. Used when the URL is needed synchronously.
  • reverse_lazy(): Returns a lazy reference to a URL string. The URL is only resolved when it's actually needed (e.g., in class-based views' success_url or in settings).
What is the purpose of the __str__() method in a Model?
  • The __str__() method returns a string representation of the object. It's used in the Django Admin Panel and when you print a model instance.
How do you handle errors and exceptions in Django views?
  • Using standard Python try-except blocks.
  • Django provides built-in views for common HTTP errors (404, 500). You can customize these by defining handlers in your project's urls.py.
What is the difference between HttpResponse and JsonResponse?
  • HttpResponse: A basic response object that can return any content type.
  • JsonResponse: A subclass of HttpResponse specifically designed for returning JSON data. It handles serialization to JSON automatically.
What is the purpose of the debug=True setting?
  • When debug=True, Django shows detailed error pages in the browser during development, including stack traces and context information. It also serves static and media files automatically. It should always be set to False in production for security reasons.
How do you configure database settings in Django?
  • In the DATABASES dictionary in settings.py, specifying the engine, name, user, password, host, and port.
What is the default database used by Django?
  • SQLite, which is included with Python. It's suitable for development but not recommended for production.
What is the purpose of the site_id setting?
  • The SITE_ID setting is used by Django's sites framework to identify the current site when running multiple sites from the same Django project.
What is the Django Sites framework?
  • A framework that allows you to manage multiple websites from a single Django project, sharing models and logic while having different domains and content.
What is the purpose of the AUTH_USER_MODEL setting?
  • AUTH_USER_MODEL specifies the custom user model to use instead of Django's default auth.User. This must be set before the first migration is run.
What are Context Processors?
  • Context processors are functions that add variables to the context of every template rendered using RequestContext. They are useful for adding common data (like user information, settings) to all templates.
What is the purpose of the TEST_RUNNER setting?
  • TEST_RUNNER specifies the class to use for discovering and running tests. Django's default test runner is usually sufficient.
How do you write tests in Django?
  • Create test classes that subclass django.test.TestCase in your app's tests.py (or separate test files).
  • Write methods that start with test_ to define individual tests.
  • Use assertion methods (e.g., assertEqual, assertTrue, assertContains) to check expected outcomes.
How do you run tests in Django?
  • python manage.py test (runs tests for all apps).
  • python manage.py test app_name (runs tests for a specific app).
What is the Django Debug Toolbar?
  • A third-party package that provides a set of panels displaying debugging information (SQL queries, request/response headers, template context, etc.) when debug=True. Very useful for development.
What is Django REST Framework (DRF)?
  • DRF is a powerful and flexible toolkit for building Web APIs using Django. It provides serializers, viewsets, authentication, permissions, and more.
What is a Serializer in DRF?
  • A Serializer is responsible for converting Django model instances or other data into representations that can be easily rendered into JSON, XML, or other content types. It also handles deserialization (parsing incoming data and validating it).
What is a ViewSet in DRF?
  • A ViewSet is a type of class-based View that groups together a set of related view actions (like list, create, retrieve, update, destroy) into a single class. Routers can automatically generate URL patterns for ViewSets.
What is the difference between a View and a ViewSet in DRF?
  • A View typically handles a single HTTP method (e.g., a GET request to retrieve a list of items, a POST request to create an item).
  • A ViewSet handles a set of related actions for a resource, often corresponding to standard CRUD operations.
How do you handle asynchronous tasks in Django?
  • Django itself is synchronous. For asynchronous tasks (like sending emails, processing images, complex calculations), you typically use a separate task queue system like Celery.
What is Django Channels?
  • Django Channels is a project that extends Django to handle WebSockets, chat protocols, IoT protocols, and other non-HTTP connections. It allows Django to handle asynchronous operations.
What is WSGI?
  • WSGI (Web Server Gateway Interface) is a standard Python interface between web servers (like Gunicorn, uWSGI) and web applications/frameworks (like Django, Flask). Django includes a built-in WSGI application.
What is ASGI?
  • ASGI (Asynchronous Server Gateway Interface) is a successor to WSGI, designed to support asynchronous web applications and frameworks. Django supports ASGI for use with Channels.
What is the recommended database for production Django applications?
  • PostgreSQL or MySQL are commonly recommended due to their robustness, features, and scalability compared to SQLite.
How do you serve static files in production?
  • Static files should be served directly by the production web server (like Nginx or Apache) or a Content Delivery Network (CDN) after being collected by collectstatic. Django's development server should not be used for serving static files in production.
How do you serve media files in production?
  • Similar to static files, media files (user uploads) should be served directly by the production web server or a CDN, after being configured via MEDIA_ROOT and MEDIA_URL.
What are the common deployment strategies for Django?
  • Using platforms like Heroku, PythonAnywhere, AWS Elastic Beanstalk, Google App Engine, DigitalOcean Droplets with manual server setup (Gunicorn/uWSGI + Nginx/Apache).
What is the purpose of the ALLOWED_HOSTS setting?
  • ALLOWED_HOSTS is a list of strings representing the host/domain names that this Django site can serve. This is a security measure to prevent HTTP Host header attacks. It must be set in production.
What is the difference between INSTALLED_APPS and other settings?
  • INSTALLED_APPS is a tuple or list of strings specifying the names of all applications that are enabled for this Django project. Other settings configure various aspects of the project and installed apps.
What is the purpose of the TEMPLATES setting?
  • The TEMPLATES setting configures Django's template engines, including the directories where templates are located and context processors.
What is the purpose of the DATABASES setting?
  • The DATABASES setting is a dictionary specifying the database connections for the project.
What is the purpose of the CACHES setting?
  • The CACHES setting configures Django's caching framework, allowing you to define different cache backends and their settings.
What is the purpose of the LOGGING setting?
  • The LOGGING setting configures Django's logging system, allowing you to define loggers, handlers, formatters, and filters.
What is the purpose of the AUTHENTICATION_BACKENDS setting?
  • AUTHENTICATION_BACKENDS is a list of authentication backend classes that Django uses to authenticate users. The default backend authenticates against the built-in user model.
What is the purpose of the MESSAGE_STORAGE setting?
  • MESSAGE_STORAGE specifies where Django's messaging framework should store messages (e.g., in sessions, in cookies).
What is the purpose of the SESSION_ENGINE setting?
  • SESSION_ENGINE specifies where Django should store session data (e.g., in the database, in files, in cache).
What is the purpose of the DEFAULT_AUTO_FIELD setting?
  • DEFAULT_AUTO_FIELD specifies the default field type to use for the primary key field on models that don't explicitly define one. Recommended to set for new projects to avoid issues with large primary key values.
What is the purpose of the CSRF_COOKIE_SECURE setting?
  • When CSRF_COOKIE_SECURE is True, the CSRF cookie will only be sent over HTTPS connections. Should be True in production.
What is the purpose of the SESSION_COOKIE_SECURE setting?
  • When SESSION_COOKIE_SECURE is True, the session cookie will only be sent over HTTPS connections. Should be True in production.
What is the purpose of the X_FRAME_OPTIONS setting?
  • X_FRAME_OPTIONS is an HTTP header that helps prevent clickjacking attacks. Setting it to 'DENY' or 'SAMEORIGIN' is recommended in production.
What is the purpose of the SECURE_SSL_REDIRECT setting?
  • When SECURE_SSL_REDIRECT is True, Django will redirect all non-HTTPS requests to HTTPS. Should be True in production.
What is the purpose of the SECURE_HSTS_SECONDS setting?
  • SECURE_HSTS_SECONDS enables HTTP Strict Transport Security (HSTS), which tells browsers to always connect to your site using HTTPS for a specified duration. Should be set to a positive value in production.
What is the purpose of the SECURE_BROWSER_XSS_FILTER setting? (Deprecated in newer Django versions)
  • This setting added the X-XSS-Protection header, which enabled XSS protection in browsers. Modern browsers handle this by default, and this setting is less relevant now.
What is the purpose of the SECURE_CONTENT_TYPE_NOSNIFF setting?
  • This setting adds the X-Content-Type-Options: nosniff header, which prevents browsers from trying to "guess" the content type of a file, potentially mitigating certain attacks. Should be True in production.
What are Template Context Processors? (revisited)
  • Functions that add data to the context of every template rendered with RequestContext.
What is the purpose of the @property decorator in Models?
  • The @property decorator allows you to define a method in a Model class that can be accessed like an attribute. This is useful for calculated fields or accessing related data concisely.
What is the purpose of the prefetch_related() method in QuerySets?
  • prefetch_related() performs a separate lookup for each relationship and does the "joining" in Python. This is useful for ManyToManyFields and Generic Relations, and can be more efficient than select_related() for retrieving related objects in bulk.
What is the purpose of the select_related() method in QuerySets?
  • select_related() "follows" foreign-key relationships and performs a JOIN in the database query to retrieve related objects in a single query. This is useful for OneToOneFields and ForeignKey relationships.
What is the difference between annotate() and aggregate()?
  • annotate(): Adds an annotation (a calculated value) to each object in a QuerySet.
  • aggregate(): Returns a dictionary of aggregated values (e.g., total count, average, sum) across the entire QuerySet, rather than for each object.
What is the purpose of the Q object in QuerySets?
  • Q objects are used to perform complex lookups that require logical operators (AND, OR, NOT) or referencing the same field multiple times.
What is the purpose of the F object in QuerySets?
  • F objects allow you to reference model fields directly within queries, enabling operations like incrementing a value or comparing two different fields on the same model instance in the database.
What are Django's built-in Generic Views (GCBVs)? (revisited)
  • Pre-written CBVs that handle common web development patterns (displaying lists, displaying details, creating, updating, deleting objects).
What is the purpose of the mixin classes in Django?
  • Mixins are classes that provide reusable functionality to other classes through multiple inheritance. In Django CBVs, mixins are used to add features like form handling, authentication requirements, or template rendering without being a complete base class.
What is the purpose of the get_context_data() method in CBVs?
  • get_context_data() is a method in CBVs (especially those inheriting from TemplateResponseMixin) that is used to populate the context dictionary passed to the template. You can override it to add custom data to the template context.
What is the purpose of the get_queryset() method in CBVs?
  • get_queryset() is a method in CBVs (especially those inheriting from ListView) that determines the QuerySet used to retrieve objects. You can override it to filter or modify the QuerySet based on request parameters or other logic.
What is the purpose of the form_valid() method in Form-handling CBVs?
  • form_valid() is a method in form-handling CBVs (like CreateView, UpdateView) that is called when a submitted form is valid. You can override it to perform actions after a successful form submission, such as saving the object and redirecting.
What is the purpose of the form_invalid() method in Form-handling CBVs?
  • form_invalid() is called when a submitted form is invalid. You can override it to perform actions when validation fails, such as re-rendering the form with error messages.
What is the purpose of the get_success_url() method in Form-handling CBVs?
  • get_success_url() is a method in form-handling CBVs that determines the URL to redirect to after a successful form submission. You can override it to dynamically generate the redirect URL.
What is the purpose of the @receiver decorator?
  • The @receiver decorator is a concise way to connect a signal handler function to a specific signal. It's an alternative to using the signal.connect() method explicitly.
What is the difference between save() and create() when working with Models?
  • create() is a shortcut method on the manager (objects) that instantiates a model, saves it to the database, and returns the object in a single step.
  • save() is a method on a model instance that saves the current state of the instance to the database. It can be used for both creating new objects (if no primary key is set) and updating existing ones.
What is the purpose of the slugify filter/function?
  • slugify converts a string into a "slug" by converting to lowercase, removing non-alphanumeric characters, and replacing spaces with hyphens. Useful for creating human-readable URLs.
How do you handle timezones in Django?
  • Configure USE_TZ = True and TIME_ZONE in settings.py. Django stores datetimes in UTC in the database and converts them to the specified timezone when retrieved.
What is the purpose of the makemigrations --empty command?
  • makemigrations --empty app_name creates an empty migration file for a specific app. This is useful for writing custom database operations that cannot be automatically generated by Django (e.g., bulk data updates, creating database views).
What is the purpose of the squashmigrations command?
  • squashmigrations app_name start_migration_name end_migration_name combines multiple migration files into a single migration file. This helps keep the number of migration files manageable over time.
What is the purpose of the runscript command? (Requires django-extensions)
  • The runscript command (from the django-extensions package) allows you to execute arbitrary Python scripts within the context of your Django project, with access to models, settings, etc. Useful for one-off tasks or cron jobs.
What is the purpose of the shell_plus command? (Requires django-extensions)
  • The shell_plus command (from django-extensions) is an enhanced version of the Django shell that automatically imports all your models, making it easier to interact with them.
What is the purpose of the dumpdata command?
  • python manage.py dumpdata app_name > file.json creates fixtures by dumping the data from your database into a file (e.g., JSON, XML, YAML). Useful for creating initial data or backing up data.
What is the purpose of the loaddata command?
  • python manage.py loaddata file.json loads data from fixtures into your database. Useful for populating the database with initial data or restoring data.
What is the purpose of the check command?
  • python manage.py check checks the entire Django project for common errors and configuration issues without running the server or tests.
What is the purpose of the dbshell command?
  • python manage.py dbshell opens the command-line client for the database engine configured in your settings.py, allowing you to interact with the database directly using SQL.
What is the purpose of the showmigrations command?
  • python manage.py showmigrations lists all migration files for each app and indicates whether they have been applied to the current database.
What is the purpose of the sqlmigrate command?
  • python manage.py sqlmigrate app_name migration_name shows the SQL statements that a specific migration will execute against the database. Useful for understanding what a migration does before applying it.
What is the difference between filter() and exclude()?
  • filter() returns a QuerySet of objects that match the given criteria.
  • exclude() returns a QuerySet of objects that *do not* match the given criteria.
What is the difference between all() and none()?
  • all() returns a QuerySet containing all objects in the model.
  • none() returns an empty QuerySet. This is useful for returning a QuerySet that can be further filtered or chained, but will never return any results.
What is the purpose of the order_by() method?
  • order_by() sorts the QuerySet by the specified model field(s). You can specify ascending or descending order (using a hyphen -).
What is the purpose of the distinct() method?
  • distinct() removes duplicate rows from the QuerySet results.
What is the purpose of the defer() and only() methods?
  • defer() excludes specified fields from being loaded when the QuerySet is evaluated.
  • only() includes only the specified fields when the QuerySet is evaluated. Both are used for performance optimization when you only need a subset of fields.
What is the purpose of the raw() method?
  • raw() allows you to execute raw SQL queries and map the results to model instances. Use with caution as it bypasses the ORM's safety features.
What is the purpose of the extra() method? (Deprecated)
  • extra() was used to inject extra SQL clauses (SELECT, WHERE, ORDER BY) into QuerySets. It is largely superseded by annotate(), filter() with Q/F objects, and raw().
What is the difference between Model.objects.create(...) and Model(...) followed by .save()?
  • create() is a single operation: instantiate and save.
  • Model(...) followed by .save() is two steps: instantiate, then save. The two-step approach is necessary if you need to perform actions or validations on the instance *before* saving it.
What is the purpose of the prefetch_related_objects() function?
  • prefetch_related_objects(list_of_objects, *lookups) is a function (not a QuerySet method) that performs the "prefetch" operation on a list of already existing model instances. Useful when you have a list of objects that weren't obtained directly from a QuerySet with prefetch_related().
What is the purpose of the bulk_create() method?
  • bulk_create(list_of_objects) efficiently inserts a list of objects into the database in a single query. Much faster than calling .save() on each object individually.
What is the purpose of the bulk_update() method?
  • bulk_update(list_of_objects, fields) efficiently updates a list of objects in the database in a single query. Specify the fields to be updated.
What is the purpose of the get_or_create() method?
  • get_or_create(**kwargs) tries to get an object based on the given keyword arguments. If an object is found, it returns the object and False. If no object is found, it creates a new object with the given arguments, saves it, and returns the object and True.
What is the purpose of the update_or_create() method?
  • update_or_create(defaults=None, **kwargs) tries to update an object based on the given keyword arguments. If an object is found, it updates its fields with values from the defaults dictionary and returns the object and False. If no object is found, it creates a new object using both the keyword arguments and the defaults, and returns the object and True.