Python Django view

01 JSON data is returned

In the real world, Python Web engineers will send back data to the front-end engineers in the form of an interface, usually called an API. The most common form of data returned is XML or JSON. Let’s take the most common JSON format as an example. How Django sends data from the database to the front desk.

Modify views.py.

From Django. shortcuts Import Render # Import JSON format data response class from Django. HTTP import JsonResponse from. Models import Blog # Def blog_list(request): blogs = blog.objects.all () blog.id, "title": blog.title} for blog in blogs] } return JsonResponse(context)Copy the code

Import the Blog class from Models in the header of the file, and then return a JsonResponse object by adding a blog_list function.

02 Creating a Route

The routing information will be added later, but this blog just needs to know how to return different data through different urls. Create a new file in the blog folder called urls.py with the following code:

from django.urls import path
import blog.views as blog_views

urlpatterns = [
    path('list/', blog_views.blog_list)
]
Copy the code

Once the code for this file is written, you need to modify the urls.py file in the my_website folder as follows:

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('blog/', include('blog.urls')),
    path('admin/', admin.site.urls),
]
Copy the code

At this point, your project file structure looks like the following, noting that the urls.py file appears twice.

Run the current application with the following command:

python manage.py runserver
Copy the code

A direct access to http://127.0.0.1:8000/ will result in the following error stating that a directory must be accessed. Enter http://127.0.0.1:8000/admin before visit blogs about the background, enter http://127.0.0.1:8000/blog/list/ get JSON data format.

The data in JSON format is as follows, and Chinese is encoded in UNICODE

You can also query directly from developer tools by clicking on the blue rectangle below.

Once the application is complete, it’s time for replay learning.

If the URL is /blog, Django automatically loads the configuration in urls.py with the following code:

urlpatterns = [
    path('blog/', include('blog.urls')),
    path('admin/', admin.site.urls),
]
Copy the code

Find the blog/ that matches the URL and load the blog.urls file with the following code:

from django.urls import path
import blog.views as blog_views

urlpatterns = [
    path('list/', blog_views.blog_list)
]
Copy the code

There is a list/ matcher included, so the blog_view.blog_list function in the view is called via blog/list/, which returns data in JSON format. Blog_view is renamed from the imported view module, with the code in the header import blog.views as blog_views.

Def blog_list(request): blogs = blog.objects.all () def blog_list(request): blogs = blog.objects.all () blog.title} for blog in blogs] } return JsonResponse(context)Copy the code

Understand the logical relationship first, then supplement the professional grammar definition.

03 Extended Details page

With this logic in mind, before implementing an interface that returns single blog data, edit the views.py file.

def detail(request, blog_id):
    blog = Blog.objects.get(id=blog_id)

    blog = {
        "id": blog.id,
        "title": blog.title,
        "content": blog.content,
        "create_time": blog.create_time
    }
    return JsonResponse(blog)
Copy the code

After modifying create_time, use the following command to rebuild sqLite.

> python manage.py makemigrations blog
Did you rename blog.creatr_time to blog.create_time (a DateField)? [y/N] y
Migrations for 'blog':
  blog\migrations\0002_auto_20210329_0940.py
    - Rename field creatr_time on blog to create_time
Copy the code

After the command is executed, run the following command:

>python manage.py migrate blog
Operations to perform:
  Apply all migrations: blog
Running migrations:
  Applying blog.0002_auto_20210329_0940... OK
Copy the code

Continue to modify the urls.py file in the blog folder as follows:

from django.urls import path
import blog.views as blog_views

urlpatterns = [
    path('list/', blog_views.blog_list),
    path('detail/<int:blog_id>', blog_views.detail)
]
Copy the code

Written after the above code, you can through the http://127.0.0.1:8000/blog/detail/1 for a single blog data acquisition, the format of the URL address to http://127.0.0.1:8000/blog/detail/ {integer number}.

Enter an integer number in the address, which can be retrieved by the blog_id in the background, which will be passed to the detail method.

Int :blog\_id an int before blog\_id is called a path converter. Common path converters include:

STR: matches any non-empty string, default; Int: matches zero or positive integers. Uuid: matches a particular type of string format; Path: Matches any non-null character that can match the path address, including /.

04 Paging Implementation

Next, extend the blog_list method to enable paging. The blog_list(request) method in views.py is mainly reformed, and the core code refers to the following content.

From Django. shortcuts Import Render # Import JSON format data response class from Django. HTTP import JsonResponse # Import paging component from django.core.paginator import Paginator from .models import Blog # Create your views here. def blog_list(request): # blogs = blog.objects.all () # blogs = blog.objects.all () # blogs = blog.objects.all () # blogs = blog.objects.all () # blogs = Blog. Blog. Title} for blogs in blogs] #} # Page_size = request.get.GET ("page", 1) # default 20 data per page Blog_all = blog.objects. all() # paginator = paginator (blog_all, Page_size) # current page current_page = paginator. Get_page (page) blogs = current_page. Object_list context = {"blog_list": [{"id": blog.id, "title": blog.title} for blog in blogs], "paginator": { "total_count": paginator.count, "num_pages": paginator.num_pages, "page_size": paginator.per_page, "page_number": current_page.number } } return JsonResponse(context)Copy the code

Paginator import paginator module from Django.core. paginator import paginator module at the top of the code to be used for subsequent pagination. The data is obtained in advance using the blog.objects.all () method, which has efficiency problems. This section will be amended.

After compiling, you can achieve paging effect through URL related parameters. Go to http://127.0.0.1:8000/blog/list/? Page =1&page_size=1

Summary of this blog post

This blog focuses on views in Django. This article focuses on function-based Views (FBV). In future blogs, we will look at class-based Views (CBV). Take the Django Rest Framework for example.