我有 2 個應用程式 Ticket 和 Comment,帶有 url: http://127.0.0.1:8000/api/tickets/<int:pk>/comments/<int:pk>/
。
評論.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的解決方案。過濾應提供僅與此工單相關的評論
uj5u.com熱心網友回復:
您覆寫該get_queryset(…)
方法:
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'])
)
對于路徑,票證的主鍵應該有不同的名稱,例如:
api/tickets/<int: ticket_pk >/comments/<int:pk>/
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/506414.html
標籤:django 休息 序列化 django-rest-framework
下一篇:質量問題不是不爆,時候未到