如何在Django ORM中编写子查询,子查询返回过滤器字段值

时间:2016-01-12 14:09:47

标签: python mysql django django-models django-orm

我想查询,以便我得到所有样本具有相同的样本类型,并且可以使用注册的最新样本定义样本类型。

我尽我所能并提出两个查询,但无法弄清楚如何将其作为单个查询。

q=Sample.objects.filter(submitted_by_id=self.request.user.id).latest('registration_time') 

queryset = Sample.objects.filter(sample_type = q.sample_type)

是否可以加入这些查询,或者我是否需要使用原始查询。

编辑: 我在get_queryset方法中使用这些查询。如果我单独执行这两个查询,它们会给出预期的输出。当我在get_queryset方法中添加它们时返回查询集给我错误: DoesNotExist:样本匹配查询不存在。 我做错了什么???

编辑:

Internal Server Error: /api/v1/samples/
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 111, in get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/views/decorators/csrf.py", line 57, in wrapped_view
return view_func(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/rest_framework/viewsets.py", line 87, in view
 return self.dispatch(request, *args, **kwargs)
 File "/usr/local/lib/python2.7/dist-packages/rest_framework/views.py", line 466, in dispatch
response = self.handle_exception(exc)
File "/usr/local/lib/python2.7/dist-packages/rest_framework/views.py", line 463, in dispatch
response = handler(request, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/rest_framework/mixins.py", line 40, in list
queryset = self.filter_queryset(self.get_queryset())
File "/home/tudip/Desktop/Raw_Desktop/ubiota/personalbiota_unmrged_with_rest_api/personalbiota/samples/views.py", line 576, in get_queryset
q=     Sample.objects.filter(submitted_by_id=self.request.user.id).latest('registration_time')
File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 502, in latest
return self._earliest_or_latest(field_name=field_name, direction="-")
File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 496, in _earliest_or_latest
return obj.get()
File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 357, in get
self.model._meta.object_name)
DoesNotExist: Sample matching query does not exist.

0 个答案:

没有答案