简体   繁体   中英

How to access dictionary values in django template

How to access the dictionary value in django template? I want to get the value of the variable a actually

class Emp(models.Model):
  name = models.CharField(max_length=255, unique=True)
  address1 = models.CharField(max_length=255)

  def get_names(self):
    names = {}
    names_desc = {}
    nbl = {}
    names.update({'a' : 1})
    names_desc.update({'b' : 2})
    nbl.update({'names' : names,'names_desc' : names_desc})
    return nbl

emp is my object that i am passing to the template Is it {{emp.get_names}}?? or {{emp.get_names.names.a}}

{{ emp.get_names.names.a }} will get you 1 in the template

{{ emp.get_names.names }} will get you {'A':1} in the template

{{ emp.get_names }} will get you {'names_desc': {'b': 2}, 'names': {'a': 1}} in the template

{{emp.get_names}}

This will return the whole 'nb1' dict.

You should go with the second one.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM