Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

678
Vistas
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?

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

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.

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda