Django去重字段

Django 去重,使用order_by 来屏蔽distinct的特性(默认加上order字段)

distinct()函数有一个隐藏特性,当使用distinct()函数的时候,如果不使用order_by()函数做跟随,那么该函数会自动把当前表中的默认排序字段作为DISTINCT的一个列

BaseModel.objects.\
filter(status=OEReviewStatusEnum.PENDING_BF_REVIEW).\
values("business_manager_id").\
distinct()

# query
SELECT DISTINCT `base_model`.`business_manager_id`, `ka_oe_entity_info`.`id` FROM `base_model` 
WHERE `base_model`.`status` = 0 ORDER BY `base_model`.`id` DESC

# model
    class BaseModel:
        business_manager_id = ...
        ...
        class Meta:
        managed = False
        db_table = 'base_model'
        ordering = ['-id']
        

# 使用order_by(‘name’)来屏蔽distinct()的特性
BaseModel.objects.\
filter(status=OEReviewStatusEnum.PENDING_BF_REVIEW).\
values("business_manager_id").\
distinct().\
order_by("business_manager_id")

# query
SELECT DISTINCT `base_model`.`business_manager_id` 
FROM `base_model` WHERE `base_model`.`status` = 0 
ORDER BY `base_model`.`business_manager_id` ASC

Django annotate

base_queryset_yesterday = AccountsInsightsHourly.objects.filter(date=date_yesterday).values("account_id"). \
            annotate(yesterday_spend=Max("spend", output_field=FloatField())). \
            values("account_id", "yesterday_spend").\
            order_by()

Buy me a 肥仔水!