Search code examples
djangoormmanytomanyfield

Django ManytoMany retireving all objects that fulfill a condition simoultaneously


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?


Solution

  • 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'))