Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django's Double Underscore

Tags:

python

django

In Django, you can make database queries like the following:

Model.objects.filter(name__icontains = 'bob')

The question is: how is this working 'under the cover'? Is the double underscore a Django thing or a Python thing? Is this just a single variable named name__icontains, or is it some sort of attribute-access syntax? In the former case, how does the filter method parse the variable name to determine that you are searching the Model table for a name that contains somewhere the string bob?

like image 570
Jonathan Gleason Avatar asked Sep 17 '11 01:09

Jonathan Gleason


People also ask

What does double underscore mean in Django?

The double underscore notation is used by Django's ORM to indicate some sort of separation in a query.

What does __ in do in Django?

The keyword after the double underscore ( __ ) in field lookup argument is so called lookup types, there are a lot of built-in lookup types that you can use, of cause you can define custom lookup types when you need, we will tell you how to create custom lookup types in other article.

What is underscore in Django?

Package and Module Names: Modules should have short, all-lowercase names. Underscores can be used in the module name if it improves readability. Python packages should also have short, all-lowercase names, although the use of underscores is discouraged.

What is a QuerySet in Django?

A QuerySet is a collection of data from a database. A QuerySet is built up as a list of objects. QuerySets makes it easier to get the data you actually need, by allowing you to filter and order the data.


1 Answers

It's a Django thing, implemented with some Python things.

In Python, you can get a dictionary of the keyword arguments passed to a function or method:

>>> def func(*args, **kwargs):
...     print(kwargs)
>>> func(a=1, b=2)
{'a': 1, 'b': 2}

From there, it can simply iterate over the dictionary keys and split them on __, and then interpret it however it wants. In this case, it takes the last part and interprets icontains as case-insensitive contains.

like image 111
icktoofay Avatar answered Oct 20 '22 16:10

icktoofay