数据查询

子查询

select * from Model_b where field in (select field in Model_a)

sub_query = Model_a.values_list('field')
queryset = Model_b.objects.filter(field__in=sub_query)

Group By

select count(field) as field_count from Model group by field

from django.db.models import Count
Model.objects.values_list('field').annotate(field_count=Count('field'))

使用SQL

Model.objects.raw("select * from model where a = %r group by field", [123])

Model转字典

注意: 若时间字段设置了auto_now_add = True, 会自动使该字段editable = False, 从而导致该函数无法正确对该字段进行转换.

解决办法: 手动为该类字段赋值

from django.forms.models import model_to_dict
data = model_to_dict(obj)
data["create_at"] = str(obj.create_at)

权限校验

方法装饰器

from django.utils.decorators import method_decorator
from guardian.decorators import permission_required_or_403

@method_decorator(permission_required_or_403("MODEL.change_TABLE"))

对象权限判断

# 是否拥有某权限
request.user.has_perm("MODEL.change_TABLE")

# 是否是管理员
request.user.is_superuser

模板函数

perms.MODEL.change_TABLE
如果觉得我的文章对你有用,请随意赞赏