Django如何使用ORM进行dinamycally OR查询

k5hmc34c  于 2023-10-21  发布在  Go
关注(0)|答案(2)|浏览(119)

这是我的SQL查询

all_or_conditions = []
if request.GET.get('filter_phone'):
      all_or_conditions.append("phone='"+request.GET.get('filter_phone')+"'")
if request.GET.get('filter_email'):
      all_or_conditions.append("email='"+request.GET.get('filter_email')+"'")
if request.GET.get('filter_whatsapp'):
      all_or_conditions.append("whatsapp='"+request.GET.get('filter_whatsapp')+"'")

sql_query = "SELECT * FROM app_table WHERE " + " OR ".join(all_or_conditions)

因此,如果只设置了一个电子邮件,

SELECT * FROM app_table WHERE email='[email protected]'

如果电子邮件和Whatspp

SELECT * FROM app_table WHERE email='[email protected]' OR whatsapp='15557776655'

所以问题是,是否有可能使用Django ORM进行这样的查询,而不是通过执行RAW查询

htrmnn0y

htrmnn0y1#

你可以动态地构建一个Q对象:

phone = request.GET.get('filter_phone')
email = request.GET.get('filter_email')
whatsapp = request.GET.get('filter_whatsapp')

q = Q(pk__in=[])  
# something result-less, not to have an empty query in your disjunction 
# that would hold for all entries

if phone:
    q |= Q(phone=phone)
if email:
    q |= Q(email=email)
if whatsapp:
    q |= Q(whatsapp=whatsapp)

qs = qs.filter(q)

请参见Always False Q object

93ze6v8z

93ze6v8z2#

可以使用from django.db.models import Q

some_model.objects.get(Q(email="email") | Q(whatsapp="1234567") | Q(phone="2341"), some_field="value")

您也可以使用&代替|进行and操作。
请在此处阅读文档以了解更多详细信息。

相关问题