简体   繁体   English

Django REST API

[英]Django REST api

I'm using Django's rest framework and currently set up I have 我正在使用Django的rest框架,目前已设置

a url /api/course/ 网址/ api / course /

which shows a list of courses that are already in the database. 它显示了数据库中已经存在的课程列表。 Courses have a Lecture foreign key and I want to make it so that you can access each course's lectures. 课程具有“讲座”外键,我想使用它,以便您可以访问每个课程的讲座。

Currently I've set it up so that /api/lectures takes you to all the lectures. 目前,我已经对其进行了设置,以便/ api / lectures带您进入所有讲座。

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

However, I'm not sure how to set it up so that when you look at course Math, you only get Math lectures.. 但是,我不确定如何设置它,以便当您观看Math课程时,您只会得到Math讲座。

Thanks! 谢谢!

Edit: My models: 编辑:我的模型:

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

So here is the answer; 所以这是答案; You can use detail route for such situations; 您可以在这种情况下使用详细路线; http://www.django-rest-framework.org/api-guide/routers/ go through DRF routing documentation; 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)

so your url will be like; 这样您的网址就会像;

/courses/id/lectures

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

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