Django – How to Make Queries and Retrieve Objects – Part 2

django related_name

Field Lookups

Field Lookups are where you actually specify the “where” clause of your SQL query.

Here I have used the __lte lookup to find the books that were published in and before 2010.

Here I have used __exact lookup to find the book whose title is “guide to the galaxy”. If you don’t provide a lookup type – that is, if your keyword argument doesn’t contain a double underscore – the lookup type is assumed to be exact. For a case-insensitive match use __iexact lookup.

Another common lookup type is __contains. There is also __icontains which is as you can imagine the case insensitive version of __contains lookup.

__startswith, __endswith, __istartswith, __iendswith are other common lookup types you will find yourself using a lot.

Here you can find a list of most used Field Lookups.

Lookups that Span Relationships

Consider this model structure below:

To retrieve Entry objects whose blog name contains ‘webmaster’ you can use the lookup below:

Note that ‘i’ here stands for case insensitive lookup.

We can also perform a reverse lookup. Line below retrieves Blog objects that which have at least one entry whose title contains ‘scripting’:

Multi-valued Relationships

Everything inside a single filter() call is applied simultaneously to filter out items matching all the requirements.

Here this part is just a little bit tricky. Below are 2 examples. In the first example, we are querying for the Blog objects that contain Entries which contain ‘webmaster’ in their titles AND which were published in 2016. Satisfying both criteria at the same time. In the second example we are querying for the Blog objects that include Entries with ‘webmaster’ in their titles as well as Blogs with Entries that were published in 2016.



See the difference?

This is the end of Part 2.

Hope this helps.
Good Luck,