60

Apologies, I am completely new to Django and Python.

I have 2 questions. First, how would I go about getting the last object created (or highest pk) in a list of objects? For example, I know that I could use the following to get the first object:

list = List.objects.all()[0]

Is there a way to get the length of List.objects? I've tried List.objects.length but to no avail.

Second, is it possible to create simultaneous filters or combine lists? Here is an example:

def findNumber(request, number)
    phone_list = Numbers.objects.filter(cell=number)

I want something like the above, but more like:

def findNumber(request, number)
    phone_list = Numbers.objects.filter(cell=number or home_phone=number)

What is the correct syntax, if any?

zdyn
  • 2,155
  • 1
  • 15
  • 17

8 Answers8

82

I haven't tried this yet, but I'd look at the latest() operator on QuerySets:

latest(field_name=None)

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

This example returns the latest Entry in the table, according to the pub_date field:

Entry.objects.latest('pub_date')

If your model's Meta specifies get_latest_by, you can leave off the field_name argument to latest(). Django will use the field specified in get_latest_by by default.

Like get(), latest() raises DoesNotExist if an object doesn't exist with the given parameters.

Note latest() exists purely for convenience and readability.

And the model docs on get_latest_by:

get_latest_by

Options.get_latest_by

The name of a DateField or DateTimeField in the model. This specifies the default field to use in your model Manager's latest method.

Example:

get_latest_by = "order_date"

See the docs for latest() for more.

Edit: Wade has a good answer on Q() operator.

Tom Leys
  • 18,473
  • 7
  • 40
  • 62
hughdbrown
  • 47,733
  • 20
  • 85
  • 108
  • @hughdbrown How can we use latest in Django template?? – MegaBytes Mar 08 '16 at 05:56
  • Note that `.latest()` will raise a `DoesNotExist exception` if the queryset is empty - see [this answer](https://stackoverflow.com/questions/73297673/what-is-the-difference-between-queryset-last-and-latest-in-django). – Jakub Holan May 20 '23 at 16:26
50

this works!

Model.objects.latest('field') - field can be id. that will be the latest id

Paul Richter
  • 10,908
  • 10
  • 52
  • 85
Harry
  • 13,091
  • 29
  • 107
  • 167
29

Since Django 1.6 - last

last()

Works like first(), but returns the last object in the queryset.

Returns the last object matched by the queryset, or None if there is no matching object. If the QuerySet has no ordering defined, then the queryset is automatically ordered by the primary key.

list = List.objects.last() gives you the last object created

punkrockpolly
  • 9,270
  • 6
  • 36
  • 37
  • Important nuance: ordering can be defined not only directly in query, but in model's Meta as well - https://docs.djangoproject.com/en/3.2/ref/models/options/#ordering – Alexey Shrub Sep 06 '21 at 07:38
20

For the largest primary key, try this:

List.objects.order_by('-pk')[0]

Note that using pk works regardless of the actual name of the field defined as your primary key.

jcdyer
  • 18,616
  • 5
  • 42
  • 49
4

You can use the count() method on a query set the get the number of items.

list = List.objects.all()
list.count()

Arguments to filter are "AND"ed together. If you need to do OR filters look at Q objects. http://docs.djangoproject.com/en/dev/topics/db/queries/#complex-lookups-with-q-objects

Wade
  • 1,058
  • 8
  • 9
0

alternative for the latest object created:

List.objects.all()[List.objects.count()-1]

It is necessary to add an AssertionError for the case when there are no items in the list.

except AssertionError:
   ...
0

I am working on Django version is 1.4.22, neither last nor lastet is working. My way to solve with minimum db loading is like:

latest = lambda model_objects, field : model_objects.values_list( field, flat = True ).order_by( "-" + field )[ 0 ]
latest_pk = latest( List.objects, "pk" )

This function accepts query_set as input.

You may bind this function dynamically by doing:

import types
List.objects.latest = types.MethodType( latest, List.objects )

Then you should be able to get the last object by this latest pk easily.

Sphynx-HenryAY
  • 746
  • 6
  • 10
0

Try this:

InsertId= (TableName.objects.last()).id
blackgreen
  • 34,072
  • 23
  • 111
  • 129
Merrin K
  • 1,602
  • 1
  • 16
  • 27