Djano's Write API uses django_rest_framework "Harry Blog"

Source: Internet
Author: User

With the Django Rest framework, you can write APIs faster and more easily, and there are a lot of tutorials on the web that are relatively simple for a master, and simply don't understand for beginners. That is you do not understand your own responsibility, as the backend, we just provide the interface can, according to the parameters provided, for the return data. So, we need friendly return data and a description.

Official website:

http://www.django-rest-framework.org/

Chinese Tutorials:

Django-rest-framework Tutorial Chinese version. pdf

OK, start learning!

First model
Class Disk (models. Model):
"""
"""
Identify = models. Charfield (max_length=64)
Description = models. Charfield (max_length=64, Default=u ' 500g*2 ')
OrgID = models. Charfield (max_length=24)

def __unicode__ (self):
Return "%s"% self.description

Class Meta:
Unique_together = (' identify ', ' orgid ')
URLs notation
From Rest_framework import routers
From Django.conf.urls import URL, include

# Create a Routing object
Router = routers. Defaultrouter ()
# Register the URL in the routing object
Router.register (R ' assets/(? p<orgid>\d+) ', views. Assetviewset)

# The first URL is our normal can, the following 2 must be this way, a word can not be wrong
Urlpatterns = [
URL (r ' ^assets/(? p<orgid>\d+)/upload$ ', Fileviews. Assetuploadviewset.as_view ()),
URL (r ' ^ ', include (Router.urls)),
URL (r ' ^api-auth/', include (' Rest_framework.urls ', namespace= ' rest_framework ')),
]

Create a serializers.py
From rest_framework import serializers
From models import Disk


Class Diskserializer (serializers. Modelserializer):
def validate (self, data):
"""
Data validation and consistency of data
"""
If not data[' identify ') or not data[' OrgID ']:
Raise serializers. ValidationError ("Must has fields:identify, OrgID")

If data[' identify ']:
If Disk.objects.filter (identify=data[' identify '), orgid=data[' OrgID ']):
Raise serializers. ValidationError ("Data is duplicated")
Return data

def create (self, validated_data):
"New"
Disk_obj = Disk.objects.create (**validated_data)
Return disk_obj

def update (self, instance, Validated_data):
"Update"
instance.identify = Validated_data.get (' identify ', instance.identify)
Instance.description = validated_data.get (' description ', instance.description)
Instance.orgid = Validated_data.get (' OrgID ', Instance.orgid)
Instance.save ()

return instance

Class Meta:
Model = Disk
Fields = "__all__"

Views and wording

From django.shortcuts import Render, get_object_or_404, get_list_or_404
From rest_framework import generics, viewsets
From Rest_framework.response Import response
From rest_framework Import permissions
From models import Disk
From serializers import Diskserializer



Class Diskviewset (Viewsets. Modelviewset):
"""
Views of the hard drive
"""
Queryset = Disk.objects.all ()
Serializer_class = Diskserializer
permission_classes = (permissions. Isauthenticatedorreadonly,)

def list (self, request, *args, **kwargs):
‘‘‘
Returns all data lists, get
‘‘‘
OrgID = self.kwargs[' OrgID ']
Self.queryset = Disk.objects.filter (Orgid=orgid)
Serializer = Diskserializer (Self.queryset, Many=true)
Return Response ({
"Status": 0,
"Data": Serializer.data,
"MSG": ""
})

Def retrieve (self, request, *args, **kwargs):
"Conditional Query"
OrgID = self.kwargs[' OrgID ']
PK = self.kwargs[' PK ']
Liaison = get_object_or_404 (Self.queryset, IDENTIFY=PK, Orgid=orgid)
Serializer = Diskserializer (liaison)

Return Response ({
"Status": 0,
"Data": Serializer.data,
"MSG": ""
})

def create (self, request, *args, **kwargs):
"" When creating a data list post, go this way "
OrgID = self.kwargs[' OrgID ']
Request.data.update ({' OrgID ': OrgID})
If Disk.objects.filter (identify=request.data[' identify '), Orgid=orgid). Count () = = 0:
Serializer = Diskserializer (Data=request.data)
Serializer.is_valid (Raise_exception=true)
Self.perform_update (Serializer)
Return Response ({
"Status": 0,
"Data": "",
"MSG": "Create Disk Liaison Success"
})
Return Response ({
"Status": 1,
"Data": "",
"MSG": "Disk Liaison existed"
})

def update (self, request, *args, **kwargs):
"' Update data, put '
partial = Kwargs.pop (' partial ', False)
OrgID = self.kwargs[' OrgID ']
PK = self.kwargs[' PK ']
Instance = get_object_or_404 (Self.queryset, IDENTIFY=PK, Orgid=orgid)
Serializer = Self.get_serializer (instance, Request.data, partial=partial)
Serializer.is_valid (Raise_exception=true)
Self.perform_update (Serializer)
Return Response ({
"Status": 0,
"Data": Serializer.data,
"MSG": ""
})

def destroy (self, request, *args, **kwargs):
"Data"
partial = Kwargs.pop (' partial ', False)
OrgID = self.kwargs[' OrgID ']
PK = self.kwargs[' PK ']
Instance = get_object_or_404 (Self.queryset, IDENTIFY=PK, Orgid=orgid)
Self.perform_destroy (instance)

Return Response ({
"Status": 0,
"Data": "",
"MSG": "Delete Memory Liaison Success"
})

Let's talk about the issues we care about.

First: Where do we get the parameters of the belt?

In the GET request is to obtain data, then we pass the data in the request object, request and Django's own, the request of rest to the data encapsulated in the request.query_params, attributes, Can be obtained using GET.

Second: How to take the parameter dynamic value of the URL?

In the request, we pass the value in the **kwargs, directly get it, remember to use get.

For more information, please visit http://www.hairuinet.com

Djano's Write API uses django_rest_framework "Harry Blog"

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.