1

I have a simple model similar to the model below:

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

The field number contains integer values generally. The user might want to use only numbers or alphanumerical codes.

The problem is I need to get the last value of the field number when the user wants to create a new ServiceInvoice instance and then add 1 to the last value. For example:

  1. Id = 1, Number = 13
  2. Id = 2, Number = 2
  3. Id = 3, Number = 16

The next item should have Id = 4 and Number = 17. However when I execute

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

It returns 2 which isn't what I want. I have tried this solution, this one and this one. Anyone of them worked for me because I need the highest number of any given ServiceInvoice.

Thanks in advance.

Community
  • 1
  • 1
tiagomenegaz
  • 141
  • 3
  • 12

2 Answers2

0

According to django docs.

Latest Returns the latest object in the table, by date, using the field_name provided as the date field.

You can do

qs = ServiceInvoice.objects.all().order_by('-number')[:1]
Rizwan Mumtaz
  • 3,875
  • 2
  • 30
  • 31
  • I tried your solution @Rizwan but it comes up with the same result. I think I need to cast number as integer because it's stored as char field (number = models.CharField). In char fields the order is like 1, 11, 111, ..., 2, 21, 211 and so on. Thank you. – tiagomenegaz Oct 15 '15 at 19:07
0

The first solution you referenced should work as long as you update the cast in your extra call to work for your database implementation. For postgresql, this should look like:

ServiceInvoice.objects.extra(
    {'number_as_int': "number::INTEGER"}
).latest('number_as_int')
Community
  • 1
  • 1
meshantz
  • 1,566
  • 10
  • 17