Django - forloop to show/filter a value to show only once the entrys

I have a model (Restrictie) in which those who voted (participanti) and those who voted (votant) are registered. If I forloop in the templates, I can see who voted for whom, but one line is displayed for each record. How can I make a forloop or query in which participants are displayed only once and next to all the voters for example:

name participanti - (name votant 1, name votant 2, ....)

Below my code

class Participanti(models.Model):
    campanievot = models.ForeignKey(Campanie, on_delete=models.CASCADE)
    nume_participant = models.CharField(max_length=200, verbose_name='nume')
    dep_participant = models.CharField(max_length=200, verbose_name='departament')
    votes = models.IntegerField(default=0)
    def __str__(self):
        return self.nume_participant

    class Meta:
        verbose_name = 'Participanti'
        verbose_name_plural = 'Participanti'

class Restrictie(models.Model):

    participanti = models.ForeignKey(Participanti,on_delete=models.CASCADE, verbose_name='Votat')
    votant = models.ForeignKey(UserVot,on_delete=models.CASCADE)

    def __str__(self):
        return str(self.participanti)

    class Meta:
        verbose_name = 'Voturi efectuate'
        verbose_name_plural = 'Voturi efectuate'

def rezultate(request):
    cineavotat = Restrictie.objects.all()

I tried this but it's show all entries like : name 1 = voters 1, name 1 = voters 2 ...

{% for p in cineavotat %}  
  {{ p.participanti }} - {{ p.votant}}
{% endfor %}

Please help me with a solution. Thank you!


def rezultate(request):
    cineavotat = Restrictie.objects.all()
    context = {'cineavotat': cineavotat}
    return render(request, 'appname/templatename.html', context)

Maybe you better to select a list of Participanti and for each of them add list of Restrictie in your view, like this:

def rezultate(request):
    cineavotat = []
    for p in Participanti.objects.all():
        cineavotat.append((p, p.restrictie_set.all()))
    return render(request, 'appname/templatename.html', {'cineavotat': cineavotat})

And then you could do this in your template

{% for participanti, restrictie in cineavotat %}  

  {{ participanti }} -
  {% for r in restrictie  %} 
  {% endfor %}  

{% endfor %}

The result is

Some Participanti - User 1; User 2; User 3;
Another Participanti - User 2; User 3;
Back to Top