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?

Upvotes: 4

Views: 2074

Answers (1)

NS0
NS0

Reputation: 6096

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.

Upvotes: 5

Related Questions