[Answered ]-ID parameter in Django REST API URL

1πŸ‘

βœ…

It’s very simple using nested routes:

Define your Article model (models/article.py):

class Article(models.Model):
    name = models.CharField(max_length=100, blank=False, null=False, default='')
    ...

Define your Comment model (models/comment.py):

class Comment(models.Model):
    content = models.CharField(max_length=100, blank=False, null=False, default='')
    article = models.ForeignKey(Article, related_name='comments', on_delete=models.CASCADE, blank=True, null=True)
    ...

Define your Article view (views/article.py):

class ArticleAPIView(viewsets.ModelViewSet):
    serializer_class = ArticleSerializer
    ....

Define your Comment view (views/comment.py):

class CommentAPIView(viewsets.ModelViewSet):
    serializer_class = CommentSerializer
    ...

Define your routes (urls.py):

from django.urls import path
from app.domain.api import views
from rest_framework_extensions.routers import ExtendedSimpleRouter

urlpatterns: list = []

router: ExtendedSimpleRouter = ExtendedSimpleRouter()
articles_router = router.register('articles', views.ArticleAPIView, basename='articles')
articles_router.register(
    'comments',
    views.CommentAPIView,
    basename='comments',
    parents_query_lookups=['article']
)
urlpatterns += router.urls

You will get routes for articles like:

{GET} /articles/          -> Get list
{GET} /articles/{id}/     -> Get by id
{POST} /articles/         -> Create
{PUT} /articles/{id}/     -> Update
{PATCH} /articles/{id}/   -> Partial update
{DELETE} /articles/{id}/  -> Delete

Finally, you will get routes for comments like:

{GET} /articles/{parent_lookup_article}/comments/          -> Get list
{GET} /articles/{parent_lookup_article}/comments/{id}/     -> Get by id
{POST} /articles/{parent_lookup_article}/comments/         -> Create
{PUT} /articles/{parent_lookup_article}/comments/{id}/     -> Update
{PATCH} /articles/{parent_lookup_article}/comments/{id}/   -> Partial update
{DELETE} /articles/{parent_lookup_article}/comments/{id}/  -> Delete

Leave a comment