RESTFUL API 提供两个应用程序之间的通信。DRF 是在 Django 之上开发的。使用 Django,您将使用 url 来提供模板(前端)与视图集之间的通信,因此无需在 django 中使用 REST API。使用 DRF urls 为外部应用程序提供端点以与您的后端通信,如移动应用程序、角度应用程序和反应。Get 方法在视图集中定义,它解释在 url 中定义的请求,例如
#Model
class Student(models.Model):
name = models.CharField(max_length=255)
age = models.IntegerField()
created_date = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.name
#Serializer
class StudentSerializer(serializers.ModelSerializer):
class Meta:
model = Student
fields = '__all__'
#Viewset
'''
For commonly perfomed operations you can use class based views to provide conformity in your APIs
'''
class StudentViewset(APIView)
#Define here your get method
def get(self,request,format=None):
student = Student.objects.all()
serializer = StudentSerializer(student)
Response(serializer.data)
##URLS
urlpatterns = [
path('api/students',StudentViewset.as_view())
]
要将您的前端连接到这个页面,就像角度一样,您将发送一个请求,例如
http.get('localhost:8000/api/student').subscribe
#Or using JQUERY YOU CAN SEND A REQUEST LIKE
$.get('localhost:8000/api/student')