0

I'm using Django Rest Framework, here's my code: models.py

class Course(models.Model):
    name = models.CharField(max_length=200)

class Formation(models.Model):
    name = models.CharField(max_length=200)
    courses = models.ManyToManyField(Course, blank=True)

serializers.py

class CourseSerializer(serializers.ModelSerializer):
    class Meta:
        model = Course
        fields = '__all__'

class FormationSerializer(serializers.ModelSerializer):
    class Meta:
        model = Formation
        fields = '__all__'
    courses = CourseSerializer(many=True)

views.py

class FormationView(viewsets.ReadOnlyModelViewSet):
    queryset = Formation.objects.all()
    serializer_class = FormationSerializer

class CourseView(viewsets.ReadOnlyModelViewSet):
    queryset = Course.objects.all()
    serializer_class = CourseSerializer

urls.py

router = routers.DefaultRouter()
router.register('formations', views.FormationView)
router.register('courses', views.CourseView)

urlpatterns = [
    path('api/', include(router.urls)),
]

When I use http://localhost:8000/api/formations/{id} it works just fine, and I can benefit from all its features (like PATCH), what I can't do though is http://localhost:8000/api/formations/{id}/courses, so also no localhost:8000/api/formations/{id}/courses/{id} and no features.

I feel like the solution is not that far, or complicated So What is the solution for this?

  • Does this answer your question? [How to implement a hierarchy of resources (eg. /parents//children) in Django REST Framework](https://stackoverflow.com/questions/17337843/how-to-implement-a-hierarchy-of-resources-eg-parents-id-children-in-django) – Ivan Starostin Mar 28 '21 at 07:39
  • also https://stackoverflow.com/questions/22194499/django-rest-framework-nested-urls-with-drf-nested-routers – Ivan Starostin Mar 28 '21 at 07:39
  • Thank you for your response, however this is manually done, and this would just give me the list of children, I can't get to one child using /parents/{id}/children/{id} or use PATCH option or stuff. I am looking for a more general and automatic way. – ABDERRAHMANE HAMMIA Mar 28 '21 at 07:57
  • 1
    I tested the second one: https://stackoverflow.com/questions/22194499/django-rest-framework-nested-urls-with-drf-nested-routers and i think it gives what I need. Thank you – ABDERRAHMANE HAMMIA Mar 28 '21 at 08:12

0 Answers0