4
Variables and attributes may not begin with underscores: 'value._id'
如何引用在Django Templates中从MongoDB获取的项目的_id
?Django模板和MongoDB _id
Variables and attributes may not begin with underscores: 'value._id'
如何引用在Django Templates中从MongoDB获取的项目的_id
?Django模板和MongoDB _id
from django import template
register = template.Library()
@register.filter(name='private')
def private(obj, attribute):
return getattr(obj, attribute)
你可以用这种方式:
{{ value|private:'_id' }}
慢多少是一个过滤器不是直接引用?我应该首先进行基准测试,还是在获取集合时使用MongoDB中的'$ project',而不是将其粗略化为'id'? (列表可能是几百个项目) – user3467349
@ user3467349如果性能真的很重要,我会使用'$ project'有一个“非专用”属性名称,因为在使用模板过滤器时,它将是一个额外的函数调用每个对象。但是,不要过早优化测量。谢谢。 – alecxe
如果将字典传递给模板而不是对象,请使用以下过滤器:'def private(dic,key):return dic [key]' –