Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/352.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Django模板和MongoDB\u id_Python_Django_Mongodb_Django Templates - Fatal编程技术网

Python Django模板和MongoDB\u id

Python Django模板和MongoDB\u id,python,django,mongodb,django-templates,Python,Django,Mongodb,Django Templates,如何引用Django模板中从MongoDB获取的项目的\u id Variables and attributes may not begin with underscores: 'value._id' 您可以这样使用它: from django import template register = template.Library() @register.filter(name='private') def private(obj, attribute): return geta

如何引用Django模板中从MongoDB获取的项目的
\u id

Variables and attributes may not begin with underscores: 'value._id'
您可以这样使用它:

from django import template

register = template.Library()

@register.filter(name='private')
def private(obj, attribute):
    return getattr(obj, attribute)

过滤器比直接引用慢多少?我应该首先对此进行基准测试,还是在获取集合时在MongoDB中使用
$project
,而不是将其粗化为“id”?(列表可能有几百项)@user3467349如果性能在这里真的很重要,我会使用
$project
来拥有一个“非私有”属性名,因为在使用模板过滤器时,每个对象都需要额外的函数调用。但是,不要过早地优化,测量。谢谢。如果将字典传递给模板而不是对象,请使用以下筛选器:
def private(dic,key):返回dic[key]
{{ value|private:'_id' }}