如何获取url参数并将其用作数据过滤器

时间:2019-12-16 04:30:06

标签: python django

我刚刚进入Python / Django,我设法构建了一个API以返回数据库表中的所有项目,但是我希望能够通过GET请求中使用的参数过滤数据。我希望能够基于数字的“作者” ID返回数据

我是根据文档构建的:

View.py

class AllTweets(APIView):
    permission_classes = [IsOwnerOrReadOnly]

    def get(self, request):
        tweets = Tweet.objects.all()
        data = TweetSerializer(tweets, many=True).data
        return Response(data)

URLs.py

urlpatterns = [
    path('', include('djoser.urls')),
    path('', include('djoser.urls.authtoken')),
    path('restricted/', restricted),
    path('create/', TweetAPIView.as_view(), name="tweet-create"),
    path('list/', AllTweets.as_view(), name="tweet-list")
 ]

Models.py

class Tweet(models.Model):
    author = models.ForeignKey(
        User, on_delete=models.CASCADE, related_name="tweets")
    tweet_text = models.CharField(max_length=200)
    created_on = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.tweet_text

1 个答案:

答案 0 :(得分:1)

您将需要在路径中添加author_id参数:

path('list/<int:author_id>', AllTweets.as_view(), name="tweet-list")

之后,您可以获取参数并对其进行过滤:

class AllTweets(APIView):
    permission_classes = [IsOwnerOrReadOnly]

    def get(self, request, author_id=None): # set as None for optional parameter
       if author_id != None:
           tweets = Tweet.objects.filter(author_id=author_id)
       else:
           tweets = Tweet.objects.all()
       data = TweetSerializer(tweets, many=True).data
       return Response(data)