Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

673
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!