0

I have 4 models: School, Class, Student, Address. I want to build an API like /api/schools/1/classes/2/students/3/address.

This example would return the address of student which has id 3, belongs to class 2 and school 1 (may be more complicated in the future).

In Java it can be done easily:

@GetMapping("/api/schools/{school-id}/classes/{class-id}/students/{student-id}/address")
public Address getAddressOf(path parameters) {
    return myService.doLookup(parameters);
}

But with DRF I don't even have any knowledge about how to achieve it since I'm very new to Python and DRF.

For now I just can write 4 ModelViewset corresponding with 4 models listed above to have very basic CRUD endpoints. How can I create my expected API?

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
SoT
  • 898
  • 1
  • 15
  • 36
  • So `student-id` is not a PK and the same `student-id` can exist in a different school and/or class and would have different address? Student address depends on school and class, right? If not then why not to handle `/api/students/{student-id}` endpoint for this case. – Ivan Starostin Jun 12 '21 at 14:05
  • Thanks for your response. But I would like to make the api as I described since I want to learn something so that I can apply to some projects in the near future. Again thank you – SoT Jun 12 '21 at 14:10
  • Given that you want to learn this and you are aware what @IvanStarostin is talking about, then you can have a look at DRF nested routers to achieve this: https://www.django-rest-framework.org/api-guide/routers/#drf-nested-routers – Brian Destura Jun 13 '21 at 09:27

0 Answers0