IMBlues / IMBlues.github.io

My legacy blog, moved to https://github.com/IMBlues/nobelium
2 stars 0 forks source link

django-orm-best-practice #7

Open utterances-bot opened 3 years ago

utterances-bot commented 3 years ago

Django ORM:天使与魔鬼

平时是小天使,出了问题就是大撒旦

https://emergencyexit.xyz/django-orm-best-practice.html

IMBlues commented 3 years ago

DRF 使用时,CharField 会自动进行 trim 操作

https://www.django-rest-framework.org/api-guide/fields/#charfield

https://github.com/encode/django-rest-framework/issues/2517

IMBlues commented 2 years ago

使用子查询提升效率

未使用子查询

# change queryset to list, not use subquery
ids = list(Employee.objects.filter(company='Private').values_list('id', flat=True))
Person.objects.filter(id__in=ids).values('name', 'age')

使用子查询

# keep queryset to query with subquery
ids = Employee.objects.filter(company='Private').values_list('id', flat=True)
Person.objects.filter(id__in=ids).values('name', 'age')
IMBlues commented 2 years ago

不加参数的 prefetch_related 也许会适得其反

由于一些核心的模型可能会在各种地方添加外键关联(比如审计),不添加参数,直接做 prefetch_related 可能会拉取到无用的表而拖慢系统。所以在使用时,一定要精确添加关联表参数

Pizza.objects.prefetch_related('toppings')