簡體   English   中英

如何在Django REST中使用外鍵字段過濾URL,正確覆蓋get_queryset方法

[英]How to filter against URL with foreign key field in Django REST, overwriting get_queryset method correctly

我正在嘗試使用django REST對一個URL過濾我的查詢集,但實際上無法使其正常工作。

我想在URL(項目名稱)中傳遞一個字符串。 根據這個外鍵字符串,我想過濾我的查詢集(BuildingGroup)。

我不想使用查詢參數,而是使用URL過濾器。 我關注了文檔,但網站上沒有太多內容。

這是我正在嘗試的:

class ListBuildingGroupProject(ListAPIView):
    serializer_class    = BuildingGroupSerializer
    filter_fields       = 'project'

    def get_queryset(self):

        project = self.kwargs['project']
        building_groups = BuildingGroup.objects.filter(project=project)
        result = building_groups.order_by('-creation_date')

        return result

這行代碼building_groups = BuildingGroup.objects.filter(project=project) throws me a KeyError for project.

Here are my models. Note that BuildingGroup has one Project. A project can belong to many BuildingGroups. 

class BuildingGroup(models.Model):
    description           = models.CharField(max_length=500, null=True, blank=True)
    project               = models.ForeignKey(Project, on_delete=models.CASCADE)
    creation_date         = models.DateTimeField(auto_now=False)
   class Project(models.Model):
       project_name            = models.CharField(max_length=120, primary_key=True, unique=True)
       start_date              = models.DateTimeField(auto_now=False, null=True, blank=True)
       end_date                = models.DateTimeField(auto_now=False, null=True, blank=True)


這是我的網址:

    path('project/<str:project_name>', ListBuildingGroupProject.as_view(), name='building-group-project'),

非常感謝您的幫助! 提前致謝!

在您的網址中,您的參數稱為project_name 這是您應該從矮人那里得到的。 另外,您希望它與project.project_name匹配:

def get_queryset(self):

    project_name = self.kwargs['project_name']
    building_groups = BuildingGroup.objects.filter(project__project_name=project_name)
    result = building_groups.order_by('-creation_date')

    return result

您可能需要查看有關此內容的DRF文檔 需要安裝Django過濾器

您只需要在一些rest_filters.py中聲明

from django_filters import rest_framework as filters
from .models import BuildingGroup
class BuildingGroupFilter(filters.FilterSet):
   class Meta:
       model = BuildingGroup
       fields = { 
           "project__name":["exact","icontains"],
           "project":["exact","in"]
       }

然后在您的ViewSet聲明中:[...]從.rest_filters導入BuildingGroupFilter

class ListBuildingGroupProject(ListAPIView):
    serializer_class=BuildingGroupSerializer
    filterset_class = BuildingGroupFilter

現在,您可以通過以下方式享受輕松的行為: {path_to_your_endpoint}?project__name__icontains="Hello World"{path_to_your_endpoint}?project__=[Project Id List]

要查看工作原理,可瀏覽的API中提供了過濾器。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM