54 Django Questions Answers
54 Django Questions Answers
Interview Questions-Answers
Connect with me:
Watch Full Video On Youtube: Youtube: https://www.youtube.com/c/nitmantalks
https://youtu.be/hMwGWqyIKEs Instagram: https://www.instagram.com/nitinmangotra/
LinkedIn: https://www.linkedin.com/in/nitin-mangotra-9a075a149/
Facebook: https://www.facebook.com/NitManTalks/
Twitter: https://twitter.com/nitinmangotra07/
Telegram: https://t.me/nitmantalks/
Query Set Based Questions: 1
By default, this command starts the development server on the internal IP at port 8000.
If you want to change the server's IP, pass it along with the port, use:
After creating a migration, to reflect changes in the database permanently execute migrate command:
python manage.py migrate
To see raw SQL query executing behind applied migration execute the command:
python manage.py sqlmigrate app_name migration_name
python manage.py sqlmigrate nitapp 0001
Users.objects.all()
where “User” is a model name.
Query Set Based Questions: 8
Users.objects.filter(name="Nitin")
where “User” is a model name.
Query Set Based Questions: 9
Users.objects.get(id=25)
where “User” is a model name.
Query Set Based Questions: 10
Let's suppose the following three querysets generated from above models, that you want to
combine.
You can use the union operator to combine two or more querysets as shown below.
2. Using Itertools:
If both querysets belong to the different model, such as query_set_1 & query_set_2 above,
then you can use itertools combine those querysets.
from itertools import chain
combined_list = list(chain(query_set_1,query_set_2))
You just need to mention the querysets you want to combine in a comma-separated manner in
chain function. You can also use it to combine more than two querysets.
combined_list = list(chain(query_set_1, query_set_2, query_set_3))
There is an issue with this approach, you won't get a queryset, you’ll get a list containing instances.
Mostly Asked Questions: 1
For Example:
❏ Here, a user requests for a resource to the Django, Django works as a controller and check to the
available resource in URL. (urls.py file)
❏ If URL maps, a view is called that interact with model and template, it renders a template.
❏ Django responds back to the user and sends a template as a response.
Mostly Asked Questions: 2
In Simple Words:
❏ A Project is the entire Django application and an App is a module inside the project that
deals with one specific use case.
For Example:- payment system(app) in the eCommerce app(Project).
A Typical Django Project Directory __init__.py: An empty file that tells Python that the current
Structure: directory should be considered as a Python package
❏ Django is called a loosely coupled framework because of its MVT architecture, which is a
variant of the MVC architecture.
❏ MVT helps in separating the server code from the client-related code.
❏ Django’s Models and Views are present on the client machine and only templates return to
the client, which are essentially HTML, CSS code and contains the required data from the
models.
❏ These components are totally independent of each other and therefore, front-end
developers and backend developers can work simultaneously on the project as these two
parts changing will have little to no effect on each other when changed.
❏ Migration in Django is to make changes to our models like deleting a model, adding a
field, etc. into your database schema.
❏ A migration in Django is a Python file that contains changes we make to our models so
that they can be converted into a database schema in our DBMS.
❏ So, instead of manually making changes to our database schema by writing queries in
our DBMS shell, we can just make changes to our models.
❏ Then, we can use Django to generate migrations from those model changes and run
those migrations to make changes to our database schema.
Mostly Asked Questions: 7
There are several commands you use to interact with Migrations In Django:
After creating a migration, to reflect changes in the database permanently execute migrate command:
python manage.py migrate
To see raw SQL query executing behind applied migration execute the command:
python manage.py sqlmigrate app_name migration_name
python manage.py sqlmigrate nitapp 0001
Let's consider a simple SQL Query where Employee table to retrieve a employee name.
By default, Django uses SQLite database. It is easy for Django users because it doesn’t require
any other type of installation.
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
Mostly Asked Questions: 9
'ENGINE': 'django.db.backends.postgresql_psycopg2',
Now we should replace the above code with our connection credentials to Mysql. The updated code should look
like the code below.
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'helloworld',
'USER': '<yourname>',
'PASSWORD': 'password',
'HOST': 'localhost',
'PORT': '',
}
}
Mostly Asked Questions: 10
prefetch_related:
❏ We use prefetch_related when we’re going to get a set of things.
❏ That means forward ManyToMany and backward ManyToMany, ForeignKey.
❏ prefetch_related does a separate lookup for each relationship, and performs the “joining” in Python.
Though both the functions are used to fetch the related fields on a model but their functioning is bit
different from each other.
In simple words, select_related uses a foreign key relationship, i.e. using join on the query itself while
on the prefetch_related there is a separate lookup and the joining on the python side.
Mostly Asked Questions: 12
```Query Executed
SELECT state_id, state_name, country_name FROM State INNER JOIN Country ON (State.country_id = Country.id)
```
Mostly Asked Questions: 13
Emp.objects.all():
In order to view all the items from your database, you can make use of the ‘all()’ function as
mentioned below:
Users.objects.all()
where Users is some class that you have created in your models
Mostly Asked Questions: 13
What Is The
Difference Between
Difference
Emp.object.filter(),
Between Emp.object.filter(),
Emp.object.get()
& Emp.objects.all()
Emp.object.get() & Emp.objects.all()
in Django Queryset?
in Django Queryset?
Emp.object.filter() & Emp.object.get():
To filter out some element from the database, you either use the get() method or the filter() method as follows:
Users.objects.filter(name="Nitin")
Users.objects.get(name="Nitin")
Basically use get() when you want to get a single unique object, &
filter() when you want to get all objects that match your lookup parameters
get() raises MultipleObjectsReturned if more than one object was found. The MultipleObjectsReturned
exception is an attribute of the model class.
get() raises a DoesNotExist exception if an object wasn't found for the given parameters. This exception is also
an attribute of the model class.
Mostly Asked Questions: 14
❏ Instagram
❏ Mozilla
❏ Spotify
❏ Pinterest
❏ Disqus
❏ Bitbucket
❏ Eventbrite
❏ Prezi
❏ Dropbox
❏ Youtube
❏ National Geographic
Mostly Asked Questions: 15
Pyramid are build for larger applications. It provides flexibility and lets the developer use the
right tools for their project. The developer can choose the database, URL structure, templating
style and more. Pyramid is heavy configurable.
Flexibility Allows complete web development More flexible as the user can select any
without the need for third-party third-party tools according to their
tools choice and requirements
Visual Debugging Does not support Visual Debug Supports Visual Debug
❏ Authorization access
❏ Managing multiple models
❏ Content management system
Common Questions: 1
django-admin:
It is the command-line utility of Django for administrative tasks.
Using the django-admin you can perform a number of tasks some of which are listed Below:
❏ django-admin version - used to check your Django version.
❏ django-admin check - used to inspect the entire Django project for common problems.
❏ django-admin runserver - Starts a light-weight Web server on the local machine for development. The
default server runs on port 8000 on the IP address 127.0.0.1. You can pass a custom IP address and port
number explicitly if you want.
❏ django-admin startapp - Creates a new Django app for the given app name within the current directory or
at the given destination.
❏ django-admin startproject - Creates a new Django project directory structure for the given project name
within the current directory or at the given destination.
❏ django-admin test - Runs tests for all installed apps.
❏ django-admin testserver - Runs a Django development server (which is also executed via the runserver
command) using data from the given fixture(s).
Common Questions: 1
Advantages Of Django:
❏ Django is a Python's framework which is easy to learn.
❏ Django follows the DRY or the Don’t Repeat Yourself Principle which means, one concept or a piece of data
should live in just one place
❏ Django Offers Better CDN connectivity and Content Management
❏ Django is a Batteries Included Framework
❏ Django Offers Rapid-development
❏ Django is highly Scalable
❏ Django provide high Security
❏ Django facilitates you to divide code modules into logical groups to make it flexible to change.
❏ Django provides auto-generated web admin to make website administration easy.
❏ Django provides template system to define HTML template for your web page to avoid code duplication.
❏ Django enables you to separate business logic from the HTML.
Common Questions: 3
Disadvantages of Django:
❏ Django is Monolithic. You must know the full system to work with it.
❏ Django's monolithic size makes it unsuitable for smaller projects
❏ Everything must be explicitly defined due to a lack of convention.
❏ Django's modules are bulky.
❏ Django is completely based on Django ORM.
❏ Components are deployed together.
Common Questions: 4
What Is The
A QuerySet
Difference
In Django?
Between Authentication And
Authorization?
S.No Authentication Authorization
In authentication process, the identity of users are checked While in authorization process, person’s or user’s authorities
1.
for providing the access to the system. are checked for accessing the resources.
2. In authentication process, users or persons are verified. While in this process, users or persons are validated.
3. It is done before the authorization process. While this process is done after the authentication process.
4. It needs usually user’s login details. While it needs user’s privilege or security levels.
Source- https://www.geeksforgeeks.org/difference-between-authentication-and-authorization/
Common Questions: 5
[Q Objects can be combined with the help of the | and & operators to get a new Q Object]
urlpatterns = [
path('', views.index), # myapp homepage
]
Common Questions: 10
The following are the significant reasons that are making REST framework perfect choice:
1. Web browsable API
2. Serialization
3. Authentication policies
4. Extensive documentation and excellent community support.
5. Perfect for web apps since they have low bandwidth.
Common Questions: 12
// settings.py
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
Common Questions: 12
❏ Session management,
❏ Use authentication
❏ Cross-site request forgery protection(CSRF)
❏ Content Gzipping
Common Questions: 13
Two key elements the Senders and the receivers are in the signals machinery. The sender is
responsible to dispatch a signal, and the receiver is the one who receives this signal and then
performs something.
Common Questions: 14
Signals Description
❏ A context in Django is a dictionary, in which keys represent variable names and values
represent their values. This dictionary (context) is passed to the template which then uses
the variables to output the dynamic content.
❏ A context is a variable name -> variable value mapping that is passed to a template.
❏ Context processors let you specify a number of variables that get set in each context
automatically – without you having to specify the variables in each render() call.
Common Questions: 16
3) Django Database Exceptions: The following exceptions are defined in django.db module.
DatabaseError: It occurs when the database is not available.
IntegrityError: It occurs when an insertion query executes.
DataError: It raises when data related issues come into the database.
4) Django Http Exceptions: The following exceptions are defined in django.http module.
UnreadablePostError: It is raised when a user cancels an upload.
Source: https://www.javatpoint.com/django-exceptions
Advanced Questions: 1
❏ Basically use get() when you want to get a single unique object, and get() throws an error
if there’s no object matching the query.
❏ If there are no results that match the query, get() will raise a DoesNotExist exception.
❏ If more than one item matches the given get() query then it’ll raise
MultipleObjectsReturned, which is also an attribute of the model class itself.
Advanced Questions: 2
As of Django 1.8
To add a TEMPLATE_CONTEXT_PROCESSORS, in the settings you must add the next code:
TEMPLATES[0]['OPTIONS']['context_processors'].append("custom_app.context_processors.categories_
processor")
Or include that string directly in the OPTIONS.context_processors key in your TEMPLATES setting.
Source:- https://stackoverflow.com/questions/17901341/django-how-to-make-a-variable-available-to-all-templates
Advanced Questions: 2
Source:- https://stackoverflow.com/questions/17901341/django-how-to-make-a-variable-available-to-all-templates
Advanced Questions: 3
❏ Django uses a very powerful format for storing URLs, that is regular expressions.
❏ RegEx or regular expression is the format for sophisticated string searching algorithms.
❏ It makes the searching process faster. Although it’s not necessary to use RegEx when
defining URLs.
❏ They can be defined as normal string also, Django server should still be able to match
them, but when you need to pass some data from the user via URL, then RegEx is used.
❏ The RegEx also makes much cleaner URLs then other formats.
Advanced Questions: 3
Example:
urlpatterns = [
path('articles/2003/', views.special_case_2003), #1
path('articles/<int:year>/', views.year_archive),#2
path('articles/<int:year>/<int:month>/', views.month_archive), #3
path('articles/<int:year>/<int:month>/<slug:slug>/', views.article_detail),#4
]
Links:
https://raturi.in/blog/designing-django-urls-best-practices/
Advanced Questions: 4
Links:
https://stackoverflow.com/questions/5870537/whats-the-difference-between-django-
onetoonefield-and-foreignkey
Advanced Questions: 5
To use the file-based sessions, you need to set the SESSION_ENGINE settings to
"django.contrib.sessions.backends.file"
Advanced Questions: 7
There are some features of Jinja templating that make it a better option than the default
template system in Django.
❏ Sandbox Execution – This is like a sandbox or a protected framework for automating the
testing process.
❏ HTML Escaping – Jinja 2 provides automatic HTML Escaping, as <, >, & characters have
special values in templates and if used as regular text, these symbols can lead to XSS
Attacks which Jinja deals with automatically.
❏ Template Inheritance
❏ Generates HTML templates much faster than default engine
❏ Easier to debug, compared to default engine.
Advanced Questions: 8
Serialization is the process of converting Django models into other formats such as XML,
JSON, etc.
Links:
https://docs.djangoproject.com/en/4.0/topics/serialization/
https://opensource.com/article/20/11/django-rest-framework-serializers
Advanced Questions: 9
Source: https://www.tutorialspoint.com/django/django_generic_views.htm
Advanced Questions: 10
What Is Mixin?
❏ Mixin is a type of multiple inheritance wherein you can combine behaviors and
attributes of more than one parent class.
❏ Mixins provide an excellent way to reuse code from multiple classes.
❏ There are two main situations where mixins are used: to provide a lot of optional
features for a class and to use one particular feature in a lot of different classes
Advanced Questions: 10
What Is Mixin?
For example, generic class-based views consist of a mixin called TemplateResponseMixin whose purpose is to
define render_to_response() method.
When this is combined with a class present in the View, the result will be a TemplateView class.
One drawback of using these mixins is that it becomes difficult to analyze what a child class is doing and which
methods to override in case of its code being too scattered between multiple classes.
Memcached Caching: The gold standard for caching. An in-memory service that can return keys at a very fast
rate. Not a good choice if your keys are very large in size
Redis: A good alternative to Memcached when you want to cache very large keys (for example, large chunks of
rendered JSON for an API)
Dynamodb Caching: Another good alternative to Memcached when you want to cache very large keys. Also
scales very well with little IT overhead.
Localmem Caching: Only use for local testing; don’t go into production with this cache type.
Database Caching: It’s rare that you’ll find a use case where the database caching makes sense. It may be useful
for local testing, but otherwise, avoid it.
File system Caching: Can be a trap. Although reading and writing files can be faster than making SQL queries, it
has some pitfalls. Each cache is local to the application server (not shared), and if you have a lot of cache keys,
you can theoretically hit the file system limit for the number of files allowed.
Dummy Caching: A great backend to use for local testing when you want your data changes to be made
immediately without caching. Be warned: permanently using dummy caching locally can hide bugs from you
until they hit an environment where caching is enabled.
Content delivery networks
Thanks! Hope It Helps You!
Thanks
PS: Don’t Forget To Connect WIth ME.
Connect with me:
Regards, Youtube: https://www.youtube.com/c/nitmantalks
Nitin Mangotra (NitMan) Instagram: https://www.instagram.com/nitinmangotra/
LinkedIn: https://www.linkedin.com/in/nitin-mangotra-9a075a149/
Facebook: https://www.facebook.com/NitManTalks/
Twitter: https://twitter.com/nitinmangotra07/
Telegram: https://t.me/nitmantalks/