问题描述
所以在django我们写了
So in django we write
Entry.objects.filter(blog__id=3)
其中看起来很丑陋,因为有时候会出现下划线太多
Which looks ugly because sometimes there are too many underscores
Entry.objects。过滤器(blog_something_ 下划线 _too_ 许多 _id = 3)
Entry.objects.filter(blog_something_underscore_too_many_id=3)
为什么django不能使用像
why django can't use syntax like
[entry.objects if blog.id=3 ]
?
我不是专家,但为什么要双重下划线?可以在python的语法中有一个更优雅的风格来写这个吗?
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?
推荐答案
Django运行在Python上,它设置了一些基本约束它涉及语法,使以下建议的语法不可能(Python不允许重新定义基本语法):
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 ]
此外,博客和id不是对象,它们引用数据库中的名称,所以将这些解释为 blog.id
也是有问题的。除非当然是以字符串的形式输入,实际上,在Python中将字符串对象作为关键字参数进行查看。这当然可以用其他方式完成,下面是一个如何使用点作为分隔符的例子:
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})
通过将这个结合到Django中的过滤器函数中,我们可以消除dotstyle函数和尴尬的**,但是我们仍然留下字典大括号,这可能是为什么它们与双重下划线。
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.
这篇关于为什么django在进行过滤器查询时必须使用双下划线?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!