0

Using the Django models examples on querymaking (https://docs.djangoproject.com/en/1.8/topics/db/queries/):

How can I select all the entries that have ALL of it's author's names starting with R using the filter function?

Marcox
  • 102
  • 10

2 Answers2

1

You use the double-underscore syntax, as described further down that page.

Entry.objects.filter(authors__name__startswith='R')

Edit

So what you actually want to do is to exclude all those authors who do not start with R. You could do that with a Q object and the ~ operator:

from django.db.models import Q
Entry.objects.exclude(~Q(authors__name__startswith='R'))
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
  • I think what he meant was all of the authors for a entry post have to have their names start with R, not just one or some of them. – Cheng May 02 '15 at 11:17
  • Yes, I meant what Cheng said. – Marcox May 02 '15 at 14:33
  • Thanks @Daniel Roseman, But for the purpose of avoiding to have to rewrite a lot of already implemented code, Do you think that there is a way of doing the same using the filterfunction (not exclude) as stated in the question? – Marcox May 02 '15 at 16:06
  • How would adding a possibly complex filter function require less rewriting than changing it to exclude? They both return a queryset. – Daniel Roseman May 02 '15 at 17:47
  • The thing is, I pass a lot of conditions to that filter (as a string) and the one that I am trying to achieve It's just another one. – Marcox May 02 '15 at 21:10
0

I can think of a one tricky solution for such a task. (not tested)

Entry.objects \
    .annotate(num_authors=Count('authors')) \
    .filter(authors__name__startswith='R')
    .annotate(num_authors_with_r=Count('authors')) \
    .filter(num_authors=F('num_authors_with_r'))

What's the idea?

  1. We get the count of all authors.
  2. Do filter
  3. Return only rows with filtered authors count == all authors count
Todor
  • 15,307
  • 5
  • 55
  • 62
  • Thanks, but tried this approach and got all the entries I had inserted even though that they authors with their name not starting with R – Marcox May 02 '15 at 22:42
  • I guess this can [eventually](https://docs.djangoproject.com/en/1.8/topics/db/aggregation/#order-of-annotate-and-filter-clauses) be considered as a `django-bug`, however I would advice you to use the **@Daniel Roseman** solution. It's far better than this one even if it worked. – Todor May 03 '15 at 08:23