Django中Q()类支持的所有可用参数有哪些?
Hey there! I totally get the frustration of hunting for a dedicated list of "parameters" for Django's Q() objects—been there myself when I was first learning how to build complex queries. Let me clear this up for you:
First off, Q() doesn't have its own unique set of parameters. Every condition you pass to Q() (like Q(question__startswith='What') or Q(name__icontains='What')) is just using Django's standard Field Lookups—the exact same ones you'd use directly in a filter(), exclude(), or get() method on a QuerySet.
Common Field Lookups You Can Use With Q()
Here's a quick breakdown of the most widely used lookups (this covers most everyday use cases):
- Exact match (default if you omit the lookup):
Q(name='Bob')(equivalent toQ(name__exact='Bob')) - Case-insensitive exact match:
Q(name__iexact='bob') - Case-sensitive contains:
Q(description__contains='django') - Case-insensitive contains:
Q(description__icontains='DJANGO') - Starts with (case-sensitive):
Q(title__startswith='Guide') - Starts with (case-insensitive):
Q(title__istartswith='guide') - Ends with (case-sensitive):
Q(filename__endswith='.py') - Ends with (case-insensitive):
Q(filename__iendswith='.PY') - Numeric comparisons:
Q(age__gt=18),Q(age__gte=21),Q(age__lt=65),Q(age__lte=60) - Value in a list:
Q(status__in=['active', 'pending']) - Null/non-null checks:
Q(email__isnull=True),Q(phone__isnull=False) - Regex matches:
Q(username__regex=r'^[A-Z]+$'),Q(username__iregex=r'^[a-z]+$')
Where to Find the Full List
Since these are standard Django field lookups, the complete, official list lives in Django's core documentation under the Field Lookups section. Some field types (like date/time fields, foreign keys) also have their own specialized lookups—for example, date fields support Q(birthdate__year=1990) or Q(event_date__month=12).
The reason you couldn't find a "Q() parameter list" is because Q() is just a wrapper that lets you combine these existing lookups with logical operators (| for OR, & for AND, ~ for NOT)—it doesn't add any new parameters of its own.
内容的提问来源于stack exchange,提问作者fires3as0n

