D
D
dsmoly2019-10-28 17:07:58
Django
dsmoly, 2019-10-28 17:07:58

Django Interaction between m2m models. How to properly organize and output in a template?

There are two models.

class Stage(models.Model):
    stageNumber = models.IntegerField()
    stageName = models.CharField()
    beginingDate = models.DateField()
    endDate = models.DateField()
    sportsmens = models.ManyToManyField(Person )
   
    def __str__(self):
        return f'{self.stageName}'

class Person(models.Model):
    class Meta:
        abstract = True

    JobNameFull = models.CharField()
    JobNameShort = models.CharField()
    sportRank = models.ForeignKey(SportRank,)
    personFIO = models.CharField()
    
    def __str__(self):
        return f'{self.personFIO}'

The view is implemented via ListView:
class StageList(ListView):
    model = Stage

    def get_queryset(self):
        return Stage.objects.all()

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['page_title'] = 'Сведения по этапам'
        return context

html template:
<table id="example" class="table display table-bordered table-striped">
                    <thead>
                    <tr>
                        <th>Порядковый номер этапа</th>
                        <th>Наименование этапа</th>
                        <th>Начало этапа</th>
                        <th>Окончание этапа</th>
                        <th>Участвующие спортсмены</th>
                    </tr>
                    </thead>
                    <tbody>
                    {% for item in object_list %}
                        <tr>
                            <td>{{ item.stageNumber }}</td>
                            <td>{{ item.stageName }}</td>
                            <td>{{ item.beginingDate }}</td>
                            <td>{{ item.endDate }}</td>
                            <td>{{ item.??? }}</td>
                        </tr>
                    {% endfor %}
                    </tbody>
                </table>

Athletes at each stage can be any number. Broke my head trying to access the intermediate table created by django for the many-to-many relationship between my models. And how to make an output in a template. I suppose that the join () method should help and it will be possible to display text containing several surnames in one cell of the table. But it doesn't work.
Any ideas how to do it?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Y
Yura Khlyan, 2019-10-28
@dsmoly

{% for person in item.sportsmen.all %}
    {{ person.JobNameFull }}
{% endfor %}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question