Django Casting Character作为整数查询

时间:2015-10-15 18:41:43

标签: django postgresql

我有一个类似于下面模型的简单模型:

class ServiceIncoice(MyCustomRegistrationModel):
    (...)
    number = models.CharField(max_length=60)
    (...)

字段编号通常包含整数值。用户可能只想使用数字或字母数字代码。

问题是,当用户想要创建新的ServiceInvoice实例然后将1添加到最后一个值时,我需要获取字段编号的最后一个值。例如:

  1. Id = 1,Number = 13
  2. Id = 2,Number = 2
  3. Id = 3,Number = 16
  4. 下一项应该有Id = 4和Number = 17.但是当我执行

    ServiceInvoice.objects.all().latest('number')
    

    它返回2并不是我想要的。我尝试过this solutionthis onethis one。他们中的任何人都为我工作,因为我需要任何给定ServiceInvoice的最高数量。

    提前致谢。

2 个答案:

答案 0 :(得分:0)

根据django docs。

Latest使用作为日期字段提供的field_name,按日期返回表中的最新对象。

你可以做到

qs = ServiceInvoice.objects.all().order_by('-number')[:1]

答案 1 :(得分:0)

您引用的first solution应该有效,只要您在额外调用中更新强制转换以便为数据库实现工作。对于postgresql,这应该是:

ServiceInvoice.objects.extra(
    {'number_as_int': "number::INTEGER"}
).latest('number_as_int')