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