Django - How can I make a list of the choices I've selected in manytomany?

38 Views Asked by At
I'm trying to make a list of the choices I've selected. In this case, the logged in Gestor will select the Funcionarios, and will be able to view the list of selected employees.

**models.py **

class Equipe(models.Model):
    gestor = models.ForeignKey(Gestor, on_delete=models.PROTECT, default="")
    funcionario = models.ManyToManyField(User)
    def __str__(self):
        return self.nome
    
    
    def get_funcionario(self):
        return "\n".join([p.funcionario for p in self.funcionario.all()])

views.py

def listaFuncionario(request):
    
    
    gest = Gestor.objects.get(user_id = request.user.id)
    equipe = Equipe.objects.filter(gestor_id = gest)
    equipes = gest.equipe_set.all()
    func = equipes.funcionario.all()
    context = {'func':func}
    return render(request, 'listaFunc.html', context)
    
    

I try, but it doesn't seem to access the selected Funcionarios table

I try but shows me

    func = equipes.funcionario.all()
AttributeError: 'QuerySet' object has no attribute 'funcionario'
[02/Nov/2022 15:15:06] "GET /funcionarios HTTP/1.1" 500 65882
n
1

There are 1 best solutions below

0
On

Your issue is coming from the views.py file, specifically these three lines:

gest = Gestor.objects.get(user_id = request.user.id)
equipes = gest.equipe_set.all()
func = equipes.funcionario.all()

Your equipes variable is derived from the gest object when you call the equipe_set.all() method which returns a QuerySet object.

Based on what you're trying to do, it looks like there was a typo, and you meant to use equipe (with no "s") instead since that variable was derived from Equipe class, which has your funcionario method defined.

I hope that helps!