Summary of common Django interview questions (2)

Continued from the previous article: /YZL40514131/article/details/125813096?spm=1001.2014.3001.5501

21. What is the difference between selected_related and prefetch_related? (important)

In Django, all Querysets are lazy, which means that when a queryset is created, there is no interaction with the database. Therefore, we can perform cascaded filter operations on the queryset. Only when the content of the Queryset is accessed, Django will actually access the database. And multi-frequency and complex database queries are often the biggest source of performance problems.
However, in our actual development, we often need to access other properties of the foreign key object. If the default query method is used to traverse the value, it will cause multiple database queries, and the efficiency can be imagined.

When querying the object collection, the specified foreign key objects are also fully loaded with the query to avoid subsequent repeated queries.
1. select_relatedApplicable to foreign key and many-to-one relational queries;
2. prefetch_relatedApplicable to one-to-many or many-to-many queries.

22. What is a cookie, how to obtain and set a cookie

Session tracking technology that retains a user
cookie is a key-value pair created by the server and then sent to the client in response.
A specific key-value ({}) stored by a browser for a server

set cookies




23. What is [session] , compare with cookie, set, get, clear session

Session is a server-side technology. Using this technology, the server can create an exclusive session object for each user’s browser at runtime. Since the session is exclusive to the user’s browser, when the user accesses the server’s web resources, The respective data can be placed in their respective sessions, and when the user accesses other web resources in the server, the other web resources take out data from the user’s respective session to serve the user.

set session

request.session[ 'username' ]= "kobe" 
request.session.set_expiry(7*24*3600)        # Set the session expiration time to one week later

get session


delete session


24. Briefly describe what is FBV and CBV

FBV (function base views) is to use functions in the view function to process requests
CBV (class base views) is to use classes in the view to process requests

Twenty-five, the difference between the command migrate and makemigrations

Generate migration files

perform migration

python migrate

26. In the view function, what are the common methods and attributes of the received request object?

request.get: query string parameter
form form parameter
request.body: non-form data
request.FILES: a dictionary-like object containing all uploaded files
request.user: request user
request.path: request url
request.method: request method

27. There are several forms of [Django ‘s Model inheritance, what are they?]

Focus: Describe abstract model classes

28. Which function in Form needs to be used to verify whether the form is submitted correctly in Django


29. What are the two characteristics of query sets? What is lazy execution (important)

*Lazy execution, caching. 
Using the same query set, a database query will occur when it is used for the first time, and then Django will cache the results. When using the query set again, the cached data will be used, reducing the number of database queries.
Create a new query set object. accomplish

30. What are the list filters returned by the query set?


31. In Django, how many ways does the server respond to the client? What are they?


Thirty-two, the difference between QueryDict and dict

*In the HttpRequest object, the GET and POST properties are instances of the django.http.QueryDict class.*
QueryDict is a dictionary-like custom class used to handle the situation where a single key corresponds to multiple values.
In python’s original dictionary, a conflict occurs when there are multiple values ​​for a key, and only the last value is kept . In HTML forms, it usually happens that a key has more than one value, such as (multi-select box) is a very common situation.****

Thirty-three, how to set a primary key for a field


Thirty-four, explain blank and null


When set to True, the field can be empty. When set to False, the field is mandatory. Character fields CharField and TextField use empty strings to store null values. If True, the field is allowed to be empty, the default is not allowed.


When set to True, django uses Null to store empty values. Date, time, and number fields do not accept empty strings. Therefore, when the IntegerField and DateTimeField fields can be set to be empty, blank and null need to be set to True.

35. How to register routes in django urlpatterns

router.register('project', view class)



Thirty-six, how to load initialization data in Django

After Django uses the save() method when creating an object, the ORM framework will convert the attributes of the object to be written into the database to initialize the database; by operating the object, querying the database, and returning the query set to the view function, Displayed on front-end pages through template language

Thirty-seven, create Django projects, Django apps, and run commands

django-admin  startproject django_project create a project 
python runserver run project 
python startapp sub-application name create sub-application 
python makemigrations sub-application name create migration script 
python migrate generate migration script 
python  manage,py createsuperuser Create admin user 
python shell terminal to debug code

38. Briefly describe the authentication process of the django rest framework. (Very important)

1 Create a sub-app

python startapp users

2 Register sub-apps

     'django.contrib.admin' ,
     'django.contrib.auth' ,
     'django.contrib.contenttypes' ,
     'django.contrib.sessions' ,
     'django.contrib.messages' ,
     'django.contrib.staticfiles' ,
     'corsheaders' ,   # Same-origin policy 
    'rest_framework' ,
     'drf_yasg' ,   # Generate interface document sub-application 
    'django_filters' ,   # DRF filter sub-application 
    'users' ,

3 Adopt JWT TOKEN certification

a Download django-restframework-jwt

pip install djangorestframework-jwt

Specify the use of jwt TOKEN authentication class in the b file

     # Specify the search engine class 
    'DEFAULT_FILTER_BACKENDS' : [ 'rest_framework.filters.SearchFilter' ,
                                 'rest_framework.filters.OrderingFilter' , ],

    # 'DEFAULT_FILTER_BACKENDS':['django_filters.rest_framework.DjangoFilterBackend'],
    # 'SEARCH_PARAM': 'se',

    # Specify the paging engine class 
    'DEFAULT_PAGINATION_CLASS' : 'rest_framework.pagination.PageNumberPagination' ,
     'PAGE_SIZE' : 3,

    # Specify the schema used to support coreapi 
    'DEFAULT_SCHEMA_CLASS' : 'rest_framework.schemas.coreapi.AutoSchema' ,

    # Specify the authentication class to use 
    # a. Specify the default authentication class (authentication method) globally 
         # 1. Specify jwt token authentication 
        'rest_framework_jwt.authentication.JSONWebTokenAuthentication' ,
         'rest_framework.authentication.SessionAuthentication' ,
         'rest_framework .authentication.BasicAuthentication' ,

4 Configure routing, you can perform user name and password authentication

global routing

urlpatterns = [

    path( 'docs/' ,include_docs_urls(title= 'Interface test platform API document' ,description= 'This is the interface platform document' )),



    re_path(r'^(?P<username>\w{6,20})/count/$', views.UsernameIsExistedView.as_view()),
    path('login/', obtain_jwt_token),


5 Rewrite the method of generating token: output the username and user id together

a. In the project public file utils, create a new file

def jwt_response_payload_handler(token,user=None,response=None):
    return {

b. It is also necessary to specify the token expiration time and the specified access path in the file. The purpose is to allow the project to find its own rewriting method when it is running;

# JWT configuration
    # Specify the token expiration time as 1 day 
    'JWT_EXPIRATION_DELTA' : datetime.timedelta(days=1),
     # Use your own jwt_response_payload_handler, the purpose is to return the username and id in the response result 
    'JWT_RESPONSE_PAYLOAD_HANDLER' : 'utils.handle_jwt_response.jwt_response_payload_handler' ,



39. How does django rest framework implement user access frequency control? (Very important)

1 Global configuration in the file, all class views that inherit APIView will take effect


         'anon' : '100/day' ,   # anonymous user 
        'user' : '10/day'

2 Local configuration (add throttle_classes = [CustomAnonRateThrottle] to the specified class view that inherits APIVIew, this class view has the current limiting function)

Create a new file in the public file

utils—–>, defines CustomAnonRateThrottle (optional), but must inherit UserRateThrottle
UserRateThrottle: indicates that it is facing the logged-in user

from rest_framework.throttling import UserRateThrottle

class CustomAnonRateThrottle(UserRateThrottle):
    THROTTLE_RATES = {"user": "5/day"}

from utils.throttle_class import CustomAnonRateThrottle

class ProjectsViewSet(viewsets.ModelViewSet):
    serializer_class = ProjectsSerializer
    pagination_class = PageNumberPagination
    permission_classes = [permissions.IsAuthenticated]
    throttle_classes = [CustomAnonRateThrottle]

    def list(self, request, *args, **kwargs):
        response=super().list(request, *args, **kwargs)
        for item in['results']:
        return response

3 tests:

Forty, what is the difference between values() and values_list()?

values ​​: take the queryset of the dictionary
values_list : take the queryset of the tuple

Leave a Comment

Your email address will not be published. Required fields are marked *