Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - Getting last object created, simultaneous filters

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?

like image 204
zdyn Avatar asked Aug 10 '09 17:08

zdyn


People also ask

What is __ GTE in Django?

The __lte lookup [Django-doc] means that you constrain the field that is should be less than or equal to the given value, whereas the __gte lookup [Django-doc] means that the field is greater than or equal to the given value.

What is __ Str__ in Django?

str function in a django model returns a string that is exactly rendered as the display name of instances for that model.

What is def __ str __( self in Django?

def str(self): is a python method which is called when we use print/str to convert object into a string. It is predefined , however can be customised.

What is _SET all () in Django?

_set is associated with reverse relation on a model. Django allows you to access reverse relations on a model. By default, Django creates a manager ( RelatedManager ) on your model to handle this, named <model>_set, where <model> is your model name in lowercase.


1 Answers

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.

like image 118
hughdbrown Avatar answered Oct 18 '22 15:10

hughdbrown