【问题标题】:Apply filter based on relationship between objects - Django-rest-framework根据对象之间的关系应用过滤器 - Django-rest-framework
【发布时间】:2018-06-22 22:26:09
【问题描述】:

我有 2 个模型。

Account:
    id, name, age, discoverable
Friendship:
    id, requestor, acceptor (requestor and acceptor are Account IDs)

我需要写2个api。

  1. 获取所有具有可发现=True 的帐户。我通过在 AccountViewSet 中对查询集应用过滤器来完成,如下所示:

    def filter_queryset(self, queryset):  
        queryset = queryset.filter(discoverable=True).all()     
        return queryset
    
  2. 使用以下 url 方案 <server-url>/accounts/1 获取帐户详细信息,其中 1 是帐户 ID。这个 api 应该返回:

    • 如果账户 1 不可发现且账户 1 与调用此 api 的经过身份验证的账户不是朋友,则为 NULL
    • 如果请求帐户和帐户 1 都是朋友,即他们在 Friendship 表中有一个条目,即使帐户 1 不可发现,它也应该返回帐户 1 的详细信息。

【问题讨论】:

    标签: django django-models django-forms django-rest-framework django-views


    【解决方案1】:

    我可以通过覆盖 AccountViewSet 的 get_object() 方法来实现它,如下所示。

    def get_object(self, queryset=None):
            """
            Fix - If account has already sent a friend request, show it even if user set 
            discoverable = False
            """
            pk = self.kwargs.get('pk', None)
            account = Account.objects.filter(id=pk).first()
            if account:
                if account.is_friends_with(self.request.user, True):
                    self.check_object_permissions(self.request, account)
                    return account
            #default handling in case they are not friends
            return super(viewsets.GenericViewSet, self).get_object()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-01-15
      • 1970-01-01
      • 2019-07-11
      • 1970-01-01
      • 2018-03-14
      • 2021-07-16
      • 2021-11-24
      • 2019-02-12
      相关资源
      最近更新 更多