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

674
Visualizações
How to filter objects with many to many relationships in django

I am new at Django and I am trying to discover many to many relationships.

I have a word model which has a many to many relationship with the default user model:

from django.db import models
from django.contrib.auth.models import User

class Word(models.Model):
    definition = models.CharField(max_length=350)
    turkish = models.CharField(max_length=50)
    english = models.CharField(max_length=50)
    users = models.ManyToManyField(User)

    def __str__(self):
        return self.english

    def summary(self):
        return self.definition[:50] + "..."

I have an example word object belonging to two users and I want only these two users to see this word object on their feedpage. How should I correct the view function below?

from django.shortcuts import render
from django.contrib.auth.models import User

@login_required
def home(request):
    user = request.user 
    small = user.username.title()
    words = Word.objects.filter(??????) #order_by('-english')
    return render(request, 'intro.html', {'words': words, 'small' : small})

Basicly, I want to check if a word object's user list contains authourized user, and if it contains, the word will be taken from database. How can I code this?

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

0

I think you should just be able to do

words = Word.objects.filter(users=user)

And to check for several users, you could do things like

words = Word.objects.filter(users__in=[user1,user2])

Have a look at the docs for examples.

about 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