postgresql Django查询集过滤器文件字段不为空

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29073390/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 01:49:49  来源:igfitidea点击:

Django queryset filter filefield not empty

pythondjangopostgresqldjango-queryset

提问by Spoutnik16

I'm trying to filter a queryset, to exclude the one with no file. And I can't get it work, except by numberless iterations.

我正在尝试过滤查询集,以排除没有文件的查询集。我不能让它工作,除非无数次迭代。

class Something(models.Model):
    name = models.CharField(max_length=512)
    file = models.FieldField(upload_to="files", null=True, blank=True)

then, to get the one with a file

然后,得到一个文件

 # this give me all objects
 Something.objects.exclude(file__exact='')

 # this is a valid solution, but hell, something easier should exist, 
 something_with_files = set()
 for s in Something.objects.all():
    if s.file:
        something_with_files.add(s)

What is the real solution to this ?

什么是真正的解决方案?

PS: working on PostGres, dunno if that can change anything at that point.

PS:在 PostGres 上工作,不知道这是否可以改变当时的任何东西。

回答by Eugene Soldatov

Exact is unnecessary here:

这里不需要精确:

Something.objects.exclude(file='')

回答by simP

There are better options, I think:

有更好的选择,我认为:

from django.db.models import Q    

Something.objects.filter(~Q(file__isnull=True))

or

或者

Something.objects.exclude(file__isnull=True)

回答by daaawx

This worked perfectly for me:

这对我来说非常有效:

objects = MyModel.objects.exclude(
    Q(file='')|Q(file=None)
)

https://books.agiliq.com/projects/django-orm-cookbook/en/latest/filefield.html

https://books.agiliq.com/projects/django-orm-cookbook/en/latest/filefield.html

回答by Daniel Roseman

Your field allows nulls, so I guess the ones without files have the field as null, not the empty string. Try this:

你的字段允许空值,所以我猜那些没有文件的字段为空,而不是空字符串。试试这个:

Something.objects.exclude(file=None)