【问题标题】:Django REST apiDjango REST API
【发布时间】:2015-11-19 17:24:45
【问题描述】:

我正在使用 Django 的 rest 框架,目前我已经设置好了

一个网址 /api/course/

它显示了数据库中已经存在的课程列表。课程有一个 Lecture 外键,我想制作它,以便您可以访问每门课程的讲座。

目前,我已将其设置为 /api/lectures 将您带到所有讲座。

router.register(r'course', views.CourseViewSet)
router.register(r'lecture', views.LectureViewSet)

但是,我不知道如何设置它,这样当您查看数学课程时,您只能获得数学讲座。..

谢谢!

编辑:我的模型:

class Lecture(models.Model):
    title = models.CharField(max_length=128, unique=True, null=True)
    recordings = models.ForeignKey(Recording, null=True)
    keywords = models.ForeignKey(Keyword, null=True)

    def __str__(self):
        return self.title

class Course(models.Model):
    title = models.CharField(max_length=128, unique=True)
    lecturer = models.CharField(max_length=128)
    lectures = models.ForeignKey(Lecture, null=True)

    def __str__(self):
        return self.title

【问题讨论】:

  • 你能展示你的模型吗?
  • @GeoJacob 当然,我已经添加了它们
  • 根据您的模型,一门课程只有一堂课。如果您想要多个讲座,那么您需要将关系更改为 manytomany。或者你必须在讲座模型中将课程作为外键字段,如果一堂课只讲课。
  • 除了将外键更改为多对多外,另一种选择是将外键从Course 模型移动到Lecture 模型。这取决于您是否希望每个讲座属于一门课程(然后将外键放在Lecture 上,或者一个讲座是否可以属于多个课程(然后使用多对多)。
  • @Alasdair 一个课程有很多讲座,所以我应该有 course = models.ForeignKey(Course) 作为 Lecture 的属性?

标签: python django api rest


【解决方案1】:

这就是答案;您可以针对这种情况使用详细路线; http://www.django-rest-framework.org/api-guide/routers/查看DRF路由文档;

class CourseViewSet(ModelViewSet):

    @detail_route(methods=['get'])
    def lectures(self, request, pk=None):
        # code to get all lectures of your current course
        # pk will be course id(ex: id of Maths course)
        data = {} # serialize the data
        return Response(data)

所以你的网址会是这样的;

/courses/id/lectures

【讨论】:

  • 我不确定我是否完全了解这里发生的事情。你能用一个更完整的例子来解释吗?抱歉,我还是新手。
猜你喜欢
  • 1970-01-01
  • 2016-02-11
  • 1970-01-01
  • 1970-01-01
  • 2018-08-28
  • 2015-02-14
  • 2014-08-28
  • 2016-02-20
  • 1970-01-01
相关资源
最近更新 更多