Search code examples
pythondjangodjango-modelsforeign-keysdjango-filter

Django - Filter objects based on their ForeignKey but with multiple choices?


I am developing an app where each User is associated with a list of languages he or she speaks. The app is about books and each Book has a language field representing the language the book is written in.

I am trying to fetch all books written in the user's languages. So if a user speaks English AND Spanish I want to retrieve all books written in English AND Spanish.

My code:

users/models.py:

class User(AbstractUser):
    languages = models.ManyToManyField(Language)

books/models.py:

class Book(models.Model):
    language = models.ForeignKey(Language)

books/views.py: This code does not actually work but I posted it to hopefully convey what I am trying to achieve:

class BooksView(APIView):
    def get(self, request):
        books = Book.objects.filter(language=request.user.languages)
        return books

Instead of Book.objects.filter(language=request.user.languages), how can I filter books based on not ONE language but MULTIPLE languages?


Solution

  • To filter using multiple values you should use __in filter - it will look for particular query in an iterable so in you case it would look like this

    class BooksView(APIView):
        def get(self, request):
            books = Book.objects.filter(language__in=request.user.languages.all())
            return books
    

    BTW logically speaking the statement "books written English AND Spanish" would imply that particular book has to be written in two versions I think you ment "books written English OR Spanish" but if that's not what you ment im sorry for that assumtion