A
A
Alexey2016-04-27 17:53:30
Django
Alexey, 2016-04-27 17:53:30

How to infer related models in django?

Good afternoon!
Please tell me how to make a selection from related models
An example of the models.py model:

class managers(models.Model):
         fio = models.CharField(max_length=100, verbose_name="ФИО")
         def get_messages(self):
    return self.messages.all()

class messages(models.Model):
        text = models.TextField()
        manager = models.ForeignKey(Managers)

urls.py example:
def index(request):
  keyWords = {
    'managers': models.managers.objects.all()
  }
  return render_to_response('index.html', keyWords)

index.html template example:
<table>
{% for manager in managers %}
     <tr>
           <td>{{ manager.fio }}</td>
           <td>
                 {% with messages=managers.get_messages %}
                        <table>
                        {% for message in messages %}
                            <tr><td>{{ message.text }}</td></tr>
                        {% endfor %}
                        </table>
                    {% endwith %}
           </td>
     </tr>
{% endfor %}
</table>

This example displays all messages for each manager.
How can I make it so that messages are displayed only for a specific manager?
Thanks in advance!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vlad, 2016-04-27
@MrSen

def get_messages(self):
    return self.messages_set.all()

and in template
{% for manager in managers %}
    {% for message in manager.get_messages  %}
          ...

The name of the classes would be with a capital letter, according to pep...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question