Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why django has to use double underscore when making filter queries?

Tags:

syntax

django

So in django we write

Entry.objects.filter(blog__id=3)

Which looks ugly because sometimes there are too many underscores

Entry.objects.filter(blog_something_underscore_too_many_id=3)

why django can't use syntax like

[entry.objects if blog.id=3 ]

?

I am not expert on this, but why must double underscore? Could there be a more elegant style in python's grammar to write this?

like image 883
est Avatar asked Mar 30 '11 03:03

est


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 is the purpose of filter () method in Django?

The filter() method is used to filter you search, and allows you to return only the rows that matches the search term.

What is underscore in Django?

The leading underscore is the commonly used function alias for the one of the ugettext functions used by the internationalization (i18n) mechanics. It means that when you have i18n running, the choicefield labels will be translated into the appropriate end-user language, if a translation is available.

What is q in Django?

Q object encapsulates a SQL expression in a Python object that can be used in database-related operations. Using Q objects we can make complex queries with less and simple code. For example, this Q object filters whether the question starts wiht 'what': from django. db.


1 Answers

Django runs on Python, which sets some basic constraints when it comes to syntax, making the following suggested syntax impossible (Python does not allow much re-definition of basic syntax):

[entry.objects if blog.id=3 ]

Also, "blog" and "id" are not objects, they refer to names in the database, so addressing these as blog.id is also problematic. Unless of course it is entered as a string, which is actually what is being done seeing as keyword arguments are passed as a dictionary objects in Python. It could of course be done in other ways, here is an example of how to use dots as separators:

def dotstyle(dict):
    retdict = {}
    for key, value in dict.items():
         retdict[key.replace(".", "__")] = value
    return retdict

Entry.objects.filter(**dotstyle({"blog.id": 3})

By incorporating this to the filter function in Django, we could do away with the dotstyle function and the awkward **, but we are still left with the dictionary braces, which is probably why they went with the double underscores instead.

like image 169
Gustav Larsson Avatar answered Oct 26 '22 14:10

Gustav Larsson