Home > Mobile >  How to get pk from url in django rest framework?
How to get pk from url in django rest framework?

Time:09-13

I have 2 apps Ticket and Comment, with url: http://127.0.0.1:8000/api/tickets/<int:pk>/comments/<int:pk>/.

comment.views

class CommentAPIList(ListCreateAPIView):
    queryset = Comment.objects.all()
    serializer_class = CommentSerializer
    permission_classes = (IsAuthenticatedOrReadOnly,)   
    pagination_class = CommentAPIListPagination

I want to get first int:pk in my url for filter my queryset, like:

queryset = Comment.objects.filter(ticket=MY_GOAL_PK)

comment.models

class Comment(models.Model):
    text = models.TextField()
    ticket = models.ForeignKey(
        Ticket,
        on_delete=models.CASCADE,
    )
    user = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
    )
    time_create = models.DateTimeField(auto_now_add=True)
    time_update = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.text

ticket.models

class Ticket(models.Model):
    title = models.CharField(max_length=150)
    text = models.TextField()
    status = models.ForeignKey(Status, on_delete=models.PROTECT, default=2)
    user = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
    )
    time_create = models.DateTimeField(auto_now_add=True)
    time_update = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.title

I don't know what other information I can give, but I can give it at your request. May be you have another solution for filtering my Comment.objects. Filtering should provide comments related only to this Ticket

CodePudding user response:

You override the get_queryset(…) method:

class CommentAPIList(ListCreateAPIView):
    queryset = Comment.objects.all()
    serializer_class = CommentSerializer
    permission_classes = (IsAuthenticatedOrReadOnly,)
    pagination_class = CommentAPIListPagination

    def get_queryset(self, *args, **kwargs):
        return (
            super()
            .get_queryset(*args, **kwargs)
            .filter(ticket_id=self.kwargs['ticket_pk'])
        )

For the path, the primary key of the ticket should have a different name, for example:

api/tickets/<int:ticket_pk>/comments/<int:pk>/
  • Related