Django template can't loop defaultdict

后端 未结 3 909
隐瞒了意图╮
隐瞒了意图╮ 2020-11-27 06:42
import collections

data = [
  {\'firstname\': \'John\', \'lastname\': \'Smith\'}, 
  {\'firstname\': \'Samantha\', \'lastname\': \'Smith\'}, 
  {\'firstname\': \'sh         


        
3条回答
  •  死守一世寂寞
    2020-11-27 07:07

    You can avoid the copy to a new dict by disabling the defaulting feature of defaultdict once you are done inserting new values:

    new_data.default_factory = None
    

    Explanation

    The template variable resolution algorithm in Django will attempt to resolve new_data.items as new_data['items'] first, which resolves to an empty list when using defaultdict(list).

    To disable the defaulting to an empty list and have Django fail on new_data['items'] then continue the resolution attempts until calling new_data.items(), the default_factory attribute of defaultdict can be set to None.

提交回复
热议问题