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.
Book.objects.get(title__exact='guide to the galaxy')
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:
blog = models.ForeignKey(Blog)
title = models.CharField(max_length=255)
body_text = models.TextField()
pub_date = models.DateField()
mod_date = models.DateField()
authors = models.ManyToManyField(Author)
def __str__(self): # __unicode__ on Python 2
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’:
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.
<span class="n">Blog</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">entry__title__contains</span><span class="o">=</span><span class="s1">'webmaster'</span><span class="p">)</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">entry__pub_date__year</span><span class="o">=</span><span class="mi">2016</span><span class="p">)</span>
See the difference?
This is the end of Part 2.
Hope this helps.