>假设我有这样的模型和自定义管理器:
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
管理器类的查询集无法访问传递给它的查询。
可以通过为模型创建两个查询管理器类来执行此操作。 见下文
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