R
R
rudikov2018-05-12 02:32:05
Django
rudikov, 2018-05-12 02:32:05

How to filter model objects in Django ORM by the number of many-to-many objects of another model associated with them?

Hello.
I understand Django ORM and I have a question about filtering in many-to-many relationships.
For example, there are two models: books and authors.

class Author(models.Model):
    name = models.CharField(max_length=100)

class Book(models.Model):
    title = models.CharField(max_length=100)
    author = models.ManyToManyField(Author)

And also given some specific author author1.
Getting this author's books is simple: author1.book_set.all()
But how do you get co-authored books by him?
Also, how to get his books when he has any specific number of co-authors (eg 2)?
Thanks in advance.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Bragin, 2018-05-12
@rudikov

An amazing thing is the documentation, so much can be found there if you search, isn't it true ;)?
https://docs.djangoproject.com/en/2.0/topics/db/ag...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question