| | 579 | .. _template-accessing-methods: |
| | 580 | |
| | 581 | Accessing method calls |
| | 582 | ====================== |
| | 583 | |
| | 584 | Most method calls attached to objects are also available from within templates. |
| | 585 | This means that templates have access to much more than just class attributes |
| | 586 | (like field names) and variables passed in from views. For example, the Django |
| | 587 | ORM provides the :ref:`"entry_set"<topics-db-queries-related>` syntax for |
| | 588 | finding a collection of objects related on a foreign key. Therefore, given |
| | 589 | a model called "comment" with a foreign key relationship to a model called |
| | 590 | "task" you can loop through all comments attached to a given task like this:: |
| | 591 | |
| | 592 | {% for comment in task.comment_set.all %} |
| | 593 | {{ comment }} |
| | 594 | {% endfor %} |
| | 595 | |
| | 596 | Similarly, :ref:`QuerySets<ref-models-querysets>` provide a ``count()`` method |
| | 597 | to count the number of objects they contain. Therefore, you can obtain a count |
| | 598 | of all comments related to the current task with:: |
| | 599 | |
| | 600 | {{ task.comment_set.all.count }} |
| | 601 | |
| | 602 | And of course you can easily access methods you've explicitly defined on your |
| | 603 | own models:: |
| | 604 | |
| | 605 | # In model |
| | 606 | class Task(models.Model): |
| | 607 | def foo(self): |
| | 608 | return "bar" |
| | 609 | |
| | 610 | # In template |
| | 611 | {{ task.foo }} |
| | 612 | |
| | 613 | Because Django intentionally limits the amount of logic processing available |
| | 614 | in the template language, it is not possible to pass arguments to method calls |
| | 615 | accessed from within templates. Data should be calculated in views, then passed |
| | 616 | to templates for display. |
| | 617 | |