我有两个应用Ticket和Comment,网址为: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
我想在我的url中获得第一个int:pk来过滤我的查询集,比如:
queryset = Comment.objects.filter(ticket=MY_GOAL_PK)
注释.型号
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
票证。型号
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
我不知道我还能提供什么其他信息,但我可以根据你的要求提供。您可能有另一个解决方案来过滤我的Comment.objects。筛选应提供仅与此票证相关的评论
覆盖get_queryset(…)
方法:
class CommentAPIList(ListCreateAPIView):
queryset = Comment.objects.all()
serializer_class = CommentSerializer
permission_classes = (IsAuthenticatedOrReadOnly,)
pagination_class = CommentAPIListPagination
defget_queryset(self, *args, **kwargs):
return (
super()
.get_queryset(*args, **kwargs)
.filter(ticket_id=self.kwargs['ticket_pk'])
)
对于路径,票证的主键应该有一个不同的名称,例如:
api/票证/<int:ticket_pk>评论/<int:pk>