简体   繁体   中英

How to call posts comments from an api

Currently I have the following Models:

class Post(models.Model):    
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    name = models.CharField(max_length=200, blank=False, null=False)

class Comment(models.Model):
    post = models.ForeignKey(Post, on_delete=models.CASCADE, null=False, blank=False)
    text = models.TextField(max_length=1000)

and these ModelViewSets:

class PostViewSet(ModelViewSet):
    queryset = Post.objects.all()
    serializer_class = PostSerializer

class CommentViewSet(ModelViewSet):
    queryset = Comment.objects.all()
    serializer_class = CommentSerializer

my question is how can I retrieve comments from a post or add new comments in a post with urls like this:

GET /posts/{id}/comments

currently I get the comments this way:

GET /comments/{id} #comment Id, not post id.

current urls.py:

from rest_framework.routers import DefaultRouter

from .views import PostViewSet, CommentViewSet

router = DefaultRouter()
router.register(r'post', PostViewSet, basename='posts')
router.register(r'comments', CommentViewSet, basename='comments')


urlpatterns = []

The first step is to create your view, In this case you will pass the postId on the URL, this argument will be available inside your view using self.kwargs[] . The get_queryset will return an queryset where you can write any logic, and serialize him.

class MessageList(generics.ListAPIView):
    serializer_class = CommentSerializer

    def get_queryset(self):
        return Comment.objects.filter(post=self.kwargs['post_id'])

Another get_queryset option is to get your post and then return the massges.

def get_queryset(self):
    return Post.objects.get(pk=self.kwargs['post_id']).comment_set.all()

Map this view to an URL, note that the name of the variable are the name used on the view.

path('posts/<post_id>/comments/', MessageList.as_view()),

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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