简体   繁体   English

如何使用(django)RESTful框架API进行自定义数据搜索

[英]how to do customized data search with a (django) RESTful framework API

With a RESTful framework, how can I define an API (or APIs) that can return a set of data for a particular search? 使用RESTful框架,如何定义可以为特定搜索返回一组数据的API(或多个API)?

For example: Say, I have 2 models as shown below 例如:说,我有2个模型,如下所示

class Student(models.Model)
  name = ....

class Subject(models.Model)
  title = ....

With the Serializer, I can return/create JSON data for both models. 使用Serializer,我可以为两个模型返回/创建JSON数据。 But what if I want an API that returns a score for a subject for a particular student? 但是,如果我想要一个返回特定学生学科得分的API怎么办?

I could solve this by providing another model and its corresponding serializer. 我可以通过提供另一个模型及其对应的序列化程序来解决此问题。

class Score(models.Model)
  student = ForeignKey(Student)
  subject = ForeignKey(Subject)
  score = IntegerField...

But the questions is what if I want to do another more "customized" search, say I want to search students who are taller than 170cm? 但是问题是,如果我想进行另一次“定制”搜索,比如说我要搜索身高超过170厘米的学生,该怎么办? Or I want to know the names of students who study subject Math? 还是我想知道学习数学课程的学生的名字? Can we use RESTful API to do these operations? 我们可以使用RESTful API来执行这些操作吗?

PS: my ultimate aim is to develop mobile apps with Django as the service side and PhoneGap (perhaps with angularjs & Ionic) in the front. PS:我的最终目标是开发以Django为服务端,并在前端开发PhoneGap(也许使用angularjs和Ionic)的移动应用程序。 I have been searching related tutorials. 我一直在寻找相关的教程。 But I can't find good complete tutorials for beginners. 但是我找不到适合初学者的完整完整教程。 Based on the information I found, I figured that employing RESTful APIs probably produce the best outcome for this develop combination? 根据我发现的信息,我认为采用RESTful API可能会为这种开发组合产生最佳结果? But the RESTful APIs do not seem to be able to do all the operations/queries. 但是RESTful API似乎无法执行所有操作/查询。 Can anyone advise me if I understand this correctly? 如果我理解正确,谁能告诉我?

I'd suggest looking into using the Django REST Framework package. 我建议您考虑使用Django REST Framework包。 It will allow you to quickly turn your models into APIs and will also add the ability to filter your models via URL query strings. 它可以让您快速将模型转换为API,还可以通过URL查询字符串添加过滤模型的功能。

Here is the documentation for Django REST Framework... http://www.django-rest-framework.org/ 这是Django REST框架的文档... http://www.django-rest-framework.org/

Take a look at the filtering docs... http://www.django-rest-framework.org/api-guide/filtering 看看过滤文档... http://www.django-rest-framework.org/api-guide/filtering

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM