简体   繁体   English

Django Aggregate Max 没有为 CharField 提供正确的最大值

[英]Django Aggregate Max doesn't give correct max for CharField

I have this query to give me the next available key from the DB.我有这个查询来给我数据库中的下一个可用密钥。 It works just fine until it get to 10, where it will say that 10 is available when it's not它工作得很好,直到达到 10,当它不可用时,它会说 10 可用

max_var = ShortUrl.objects.filter(is_custom=False).aggregate(max=Cast(Coalesce(Max('key'), 0),BigIntegerField()))['max'] + 1

The column is a CharField.该列是一个 CharField。

Any tips on how to fix this?有关如何解决此问题的任何提示?

You need to annotate (cast string to int) first.您需要先注释(将字符串转换为 int)。 Then you can find the aggregate of casted value.然后你可以找到铸造价值的聚合 ie: IE:

from django.db.models import BigIntegerField
from django.db.models.functions import Cast
from django.db.models import Max

max_var = ShortUrl.objects.filter(is_custom=False) \
    .annotate(key_int = Cast('key', output_field=BigIntegerField())) \
    .aggregate(max=Max('key_int'))['max'] or 0

max_var+=1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM