gpt4 book ai didi

python - Django 模型中的默认过滤器

转载 作者:太空狗 更新时间:2023-10-29 21:13:51 25 4
gpt4 key购买 nike

是否可以在 Django 模型中设置默认过滤器?

类似于:

class MyModel(models.Model):
timestamp = models.DateTimeField(default=datetime.utcnow)
active = models.BooleanField(default=True)

class Meta:
ordering = ['-timestamp']
filtering = [active=True]

最佳答案

您必须覆盖 manager :

class MyModelManager(models.Manager):
def get_queryset(self):
return super(MyModelManager, self).get_queryset().filter(active=True)

class MyModel(models.Model):
timestamp = models.DateTimeField(default=datetime.utcnow)
active = models.BooleanField(default=True)

objects = MyModelManager()

class Meta:
ordering = ['-timestamp']

get_queryset 在 Django 1.6 之前是 get_query_set

关于python - Django 模型中的默认过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14925090/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com