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?
The double underscore notation is used by Django's ORM to indicate some sort of separation in a query.
The filter() method is used to filter you search, and allows you to return only the rows that matches the search term.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With