【发布时间】:2019-12-25 11:42:37
【问题描述】:
我正在尝试使用 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'),
非常感谢您的帮助!提前致谢!
【问题讨论】:
-
building_groups = BuildingGroup.objects.filter(project__project_name=project)? -
@RaideR 感谢您的提示,它仍然给了我关键错误。我认为
self.kwargs['project']没有访问我在 URL 中传递的参数.... 或者我通常不正确地使用过滤器?
标签: python django django-rest-framework django-filter