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

妖精的绣舞 提交于 2020-01-01 11:55:08

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/5481682/why-django-has-to-use-double-underscore-when-making-filter-queries

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!