How the Django Rest framework handles foreign keys when inserting data into a database

Source: Internet
Author: User

I. in models.py

 from Import Models class Usermodel (models. Model)    = models. Charfield ()class  MyModel (models. Model)    = models. ForeignKey (user)    = models. Charfield ()

Two. Creating a serialization class in a serialized file serializers.py

 fromRest_framework.serializersImportSerializer fromModelsImportMyModelclassMyserializer (serializer.modelserializers):#Custom FieldsUser_name =serializers. Serializermethodfield ()classMeta:model=MyModel Fields= ("user_name"," Age")        #handle custom fields return user name, get Usermodel data by foreign key    defget_user_name (self, obj):returnObj.user.user_namedefCreate (self, validated_data)
# Handling foreign key fieldsreturnMyModel.objects.create (author=self.context["author"], **validated_data)

Three. view file views.py defined in view

#in the View function fromRest_framework.viewsImportApiview#used in Class View, integrated from this class fromRest_framework.decoratorsImportApi_view#method View is used, is an adorner, direct decorating method View fromRest_frameworkImportStatus fromRest_framework.responseImportResponse#Direct conversion of dictionary data to JSON data fromModelsImportMyModel fromserializersImportMyserializer fromRest_framework.requestImportRequest fromRest_frameworkImportExceptions@api_view (['GET','POST','PUT','DELETE'])#indicates that requests are allowed in the requested mannerdefapi_list (Request):    ifRequest.method = ='GET':        #querying data from a database to get a query set        Try: Query_set=MyModel.objects.all ()exceptsnippet.doesnotexist:returnResponse (status=status. http_417_expectation_failed)#invokes the serialized class object, returns the serialized field collection, and obtains the data using the Serializers.data methodserializers = Myserializer (Query_set, many=True)#The data is fetched, returned to the client, and Response () converts the data into JSON data.        returnResponse (Serializers.data, status=status. HTTP_200_OK)#The front-end submits the data, invokes the model, and saves it to the database    elifRequest.method = ='POST':
user = Request.user#inserting the foreign key dataSerializer = Myserializer (data=Request.data, context={"author": User})#if the deserialized object exists, it means that the data is valid and the data is saved to the database ifserializer.is_valid ():#call Save () to invoke the Create () method of the serialized object, creating a piece of dataSerializer.save ()returnResponse (Serializer.data, status=status. HTTP_200_OK)returnResponse (Serializer.errors, Status=status. Http_400_bad_request)

How the Django Rest framework handles foreign keys when inserting data into a database

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.