use*_*817 24 django django-queryset
我需要创建一个查询集并手动添加一些我从不同查询结果中获得的对象,以便在表中显示它.我使用xx = set()但它没有完成这项工作.
kar*_*ikr 26
您可以通过以下方式之一进行操作:
from itertools import chain
#compute the list dynamically here:
my_obj_list = list(obj1, obj2, ...)
#and then
none_qs = MyModel.objects.none()
qs = list(chain(none_qs, my_obj_list))
Run Code Online (Sandbox Code Playgroud)
你也可以这样做:
none_qs = MyModel.objects.none()
qs = none_qs | sub_qs_1 | sub_qs_2
Run Code Online (Sandbox Code Playgroud)
然而,这不是对切片查询集工作
Dan*_*man 11
你不能这样做.查询集是数据库查询的表示.您无法手动向其添加项目.
但是如果你需要任意有序的模型实例集合,只需使用一个列表.
我真的迟到了,但是为了将来的参考,您可以创建一个查询集,然后对具有特定属性的对象进行过滤.
Model.objects.filter(foo='bar')
Model.objects.exclude(foo='bar')
Run Code Online (Sandbox Code Playgroud)
def return_queryset_with_desired_objects(self):
qs = SomeModel.objects.all()
wanted_ids = [obj.id for obj in qs if obj.foo]
return self.filter(id__in=wanted_ids]
def return_queryset_without_undesired_objects(self):
qs = SomeModel.objects.all()
unwanted_ids = [obj.id for obj in qs if not obj.foo]
return self.exclude(id__in=unwanted_ids]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
33785 次 |
| 最近记录: |