假设我有这样的模型和自定义管理器:
class FooManager(models.Manager):
def get_query_set(self):
super(FooManager, self).get_query_set()
class Foo(models.Model):
name = models.CharField(max_length=10)
status = models.BooleanField(default=False)
objects = FooManager()
我觉得这应该很简单,但是通过文档和“自我”来看,我可能错过了一些明显的东西。我的问题是如何根据实际查询过程中传递的查询返回对象/查询集?
例如:
objs = Foo.objects.all()
print(objs, "Objects queryset only with status set to True")
objs = Foo.objects.filter(name__icontains='a')
print(objs, "Objects queryset with 'a' in name and status set to True")
objs = Foo.objects.filter(name__icontains='a', status=False)
print(objs, "Objects queryset with 'a' in name and status set to False")
我可以想象像这样的样本:
class FooManager(models.Manager):
def get_query_set(self):
status = self.passed_lookups['status']
queryset = super(FooManager, self).get_query_set()
if status is None:
queryset = queryset.filter(status=True)
else:
queryset = queryset.filter(status=status)
return queryset
答案 0 :(得分:0)
管理器类的查询集无法访问传递给它的查询。
您可以通过为模型创建两个查询管理器类来做到这一点。见下文
class FooManager(models.Manager):
def get_query_set(self):
super(FooManager, self).get_query_set().filter(status=True)
class Foo(models.Model):
name = models.CharField(max_length=10)
status = models.BooleanField(default=False)
objects = FooManager()
all_objects = models.Manager()
在代码中,您要过滤状态时必须使用Foo.objects.filter
,而不想过滤状态时必须使用Foo.all_objects