[Fixed]-Filter many to many field in django

1👍

You are probably looking for the __gt modifier. ManyToManyFields can be queried and filtered like regular fields, and filtering on a field in the related model just requires a dunderscore (__).

This query should work to get all Products with a start date after today:

import datetime
Product.objects.filter(start_end_dates__start_date__gt=datetime.now())

Based on the edit if you need a list of Products that have start dates that are all after ‘now’, then thats just a matter of some boolean fiddling:

A “product that has all ranges with a start greater than now” is equivalent to “a product that has does not have any ranges less than now”. Which can be done with a Q object:

from django.db.models import Q
Product.objects.filter(~Q(start_end_dates__start_date__lte=datetime.now()))

The section ~Q(...) is in effect saying “not this query (the ~)”, so its saying:

Filter Products by those that have not got a start_end_dates with a start_date less than today.

Leave a comment