Accessing dataclass properties by name in Django template

Viewed 28

In Django, I have created a dataclass to help me move data around in a standardized way:

# models.py
class Person(models.Model):
  name = CharField(max_length=50)

#utils.py
@dataclass
class Performance:
  person: Person
  last_year: int
  five_years: int

The idea here is that I can access the properties by name when transferring them to the template:

#views.py
class IndexView(View):
  def get(self, request):
    persons = Person.objects.filter(name="pam")
    perfs_array = []

    for person in persons:
      p = Performance()
      p.last_year = #some math
      p.five_years = #more math
      perfs_array.append(p)
    
    context = {"perfs": perfs_array}
    return render(...) 

The goal is to be able to do this:

<!--index.html-->
{% for perf in perfs %}
  <h1>{{ perf.person.name }}</h1>
  <p>last year's performance: {{ p.last_year }}</p>
{% endfor %}

However, I can only access the data using numbered indices:

<!--index.html-->
{% for perf in perfs %}
  <h1>{{ perf.0.name }}</h1>
  <p>last year's performance: {{ p.1 }}</p>
{% endfor %}

This made it very hard to write correct code and to debug the templates when things go inevitably south. Is there a way to access the data with named indices?

Thanks!

0 Answers
Related