Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

1K
Visualizações
How can I access to data stored in a ManyToMany related table in Django?

I want to make a query to obtain all the users that another user is "following" for a learning project.

When I execute the following python code:

user = User.objects.get(id=user_id)
followers = user.follows.all()

I don't get an error but instead I get a list with an object ( called Follow object (4) ) from which I can't access the user related properties.

I've checked this documentation here: https://docs.djangoproject.com/en/3.2/topics/db/examples/many_to_many/

But I can't find where I'm failing to use properly this type of model-relation.

Here are my Django models:

class User(AbstractUser):
    pass

class Follow(models.Model):
    user = models.ForeignKey(User, null=False, on_delete=models.CASCADE, related_name="follows")
    follow = models.ManyToManyField(User, blank=True, related_name="followed_by")

I searched in my Django DB to see what is happening and I saw that there is a relational table called "network_follow_follow" that in fact has all the info that I need and is related with the object that I get from my Query, here are two pictures about the table that I can access and the one that I don't know how to access: Table data requested by my code:
Table data requested by my code

Table that I need to query:
Table that I need to query

So now I'm looking a way to access that last table, but to know how can I access straight forward to the last table data would be much better I think.

Thanks in advance.

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

See if this works for you.

follow_object = Follow.objects.filter(user=user)
followers_of_user = follow_object.follow.all()

I think the problem is that the user object does not have a user.follows function. You have created a seperate table in the database with that relationship data. I'm sure there's a better way of doing it but that's what I have done with something similar in my project.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda