无法在Django中筛选空字段。

huangapple go评论94阅读模式
英文:

Can't filter empty fields in Django

问题

以下是要翻译的内容:

  1. 我想要获取在我的数据库中提供了电子邮件的用户列表使用Django
  2. 这是我的查询

list(App.objects.exclude(admins__email__exact='').values('admins__email'))

  1. 奇怪的是,它排除了一切,并返回:`[]`
  2. 尽管当我运行:`list(App.objects.all().values('admins__email'))` 时,我可以看到一个用户电子邮件列表,并且其中并非所有都为空:
  3. ```python
  4. [{'admins__email': 'example@gmail.com'},
  5. {'admins__email': ''},
  6. {'admins__email': ''},
  7. {'admins__email': ''},
  8. {'admins__email': 'example2@gmail.com'},
  9. {'admins__email': 'example3@gmail.com'},
  10. {'admins__email': ''},
  11. ...]

我希望得到这个列表:

  1. [{'admins__email': 'example@gmail.com'},
  2. {'admins__email': 'example2@gmail.com'},
  3. {'admins__email': 'example3@gmail.com'}]

附注:不知何故,我可以使用 list(User.objects.exclude(email__exact='').values('email')) 获取正确的列表,但在这个上下文中,我需要对我的 App 应用一些过滤器,因此我需要让第一个查询起作用。

英文:

I want to get a list of users that have provided an email in my database using Django.

This is my query:

list(App.objects.exclude(admins__email__exact='').values('admins__email'))

which strangely excludes everything and gives: []

although when I run: list(App.objects.all().values('admins__email')) i can see a list of user emails and NOT all of them are empty:

  1. [{'admins__email': 'example@gamil.com'},
  2. {'admins__email': ''},
  3. {'admins__email': ''},
  4. {'admins__email': ''},
  5. {'admins__email': 'example2@gamil.com'},
  6. {'admins__email': 'example3@gamil.com'},
  7. {'admins__email': ''},
  8. ...]

i expect to get this list:

  1. [{'admins__email': 'example@gamil.com'},
  2. {'admins__email': 'example2@gamil.com'},
  3. {'admins__email': 'example3@gamil.com'}]

ps: somehow I can get the correct list with list(User.objects.exclude(email__exact='').values('email')) but in this context, I need to apply some filters to my App and therefore I need to get the first query to work.

答案1

得分: 1

我终于以这种方式使它工作了:

  1. list(App.objects.filter(admins__email__regex='.').values('admins__email'))

尽管我觉得__exact=''不起作用有点奇怪。对我来说似乎是Django的一个bug。

英文:

I finally got it working this way:

  1. list(App.objects.filter(admins__email__regex='.').values('admins__email'))

although I find it odd that __exact='' is not working. seems like a Django bug to me.

答案2

得分: 0

尝试这个:

  1. User.objects.exclude(email__isnull=True).exclude(email__exact='')
英文:

Try this

  1. User.objects.exclude(email__isnull=True).exclude(email__exact='')

huangapple
  • 本文由 发表于 2023年2月14日 20:08:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/75447627.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定