Python Django模板和MongoDB\u id
如何引用Django模板中从MongoDB获取的项目的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
\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' }}