
Advanced QuerySets
Lookups, Q objects, F expressions, aggregation, annotations, select_related, prefetch_related
1Which lookup allows filtering objects where a field contains a specific string, case-insensitively?
Which lookup allows filtering objects where a field contains a specific string, case-insensitively?
回答
The icontains lookup performs a case-insensitive search to check if a field contains a substring. The 'i' prefix in icontains indicates that the comparison ignores case, which is useful for user searches where case may vary.
2What is the main difference between select_related and prefetch_related?
What is the main difference between select_related and prefetch_related?
回答
select_related uses a SQL JOIN to retrieve related objects in a single query, but only works for ForeignKey and OneToOne relationships. prefetch_related performs separate queries then links objects in Python, making it suitable for ManyToMany and reverse ForeignKey relationships.
3Which Django object allows combining filter conditions with an OR operator?
Which Django object allows combining filter conditions with an OR operator?
回答
Q objects allow building complex queries by combining conditions with | (OR), & (AND) and ~ (NOT) operators. Without Q objects, chained filter() calls only apply AND conditions, making it impossible to create OR queries directly.
What is the main advantage of using F() expressions instead of Python values in an update?
Which aggregation method returns a dictionary with calculated values instead of a QuerySet?
+22 面接問題