Python Django为什么要添加';不为空';ToSQL子句?
我有一个模型:Python Django为什么要添加';不为空';ToSQL子句?,python,django,Python,Django,我有一个模型: class Profile: ... phone = models.CharField(max_length=50, blank=True, null=True) ... 当我运行queryset时: Profile.objects.exclude(phone='', phone__isnull=True).values('phone') 它创建SQL代码: SELECT "user_profile_profile"."phone" FROM "use
class Profile:
...
phone = models.CharField(max_length=50, blank=True, null=True)
...
当我运行queryset时:
Profile.objects.exclude(phone='', phone__isnull=True).values('phone')
它创建SQL代码:
SELECT "user_profile_profile"."phone" FROM "user_profile_profile" WHERE NOT ("user_profile_profile"."phone" IS NULL AND "user_profile_profile"."phone" = '' AND "user_profile_profile"."phone" IS NOT NULL); args=('',)
它是错误的,因为它返回所有phone include phone=None和phone=''。您需要将
排除
条件分为两部分:
Profile.objects.exclude(phone='').exclude(phone__isnull=True).values('phone')
或者使用Q
对象
from django.db.models import Q
Profile.objects.exclude(Q(phone='')|Q(phone__isnull=True)).values('phone')
你到底想查询什么?我希望它是
而不是(“用户配置文件”;“电话”=”)而不是(“用户配置文件”;“电话”为空)
。为什么添加了“user\u profile\u profile”。“phone”不是空的?