Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defining django queryset with Q objects with foreign key

Example model:

class Book(models.Model):
    title = models.TextField()

class Author(models.Model):
    book = models.ForeignKey(Book)
    name = models.CharField(max_length=50)

and some example data:

Book:
id  title
1   test111
2   test222
3   test333
4   test444

Author:
book_id  name
1        test111
1        test222
2        test222
2        test333
3        test111
3        test333
4        test111
4        test333

I want get all books which authors name contains '111' and '333' (so all books which have at least 2 authors: first with 111 in name, second with 333 in name)

I can reach this goal by using chain query:

books = Book.objects.filter(author__name__icontains="111").filter(author__name__icontains="333")

which return two books with id: 3 and 4

Is there any way to reach above goal by using Q objects?

like image 249
Lukasz Koziara Avatar asked Nov 18 '25 10:11

Lukasz Koziara


1 Answers

You can combine reduce and Q, see The power of django’s Q objects post.

from django.db.models import Q
import operator
auths = [ "111", "333" ]
query = reduce(operator.and_, [ Q(author__name__icontains=x) for x in auths ] )
books = Book.objects.filter( query )
like image 183
dani herrera Avatar answered Nov 20 '25 06:11

dani herrera



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!