[Fixed]-Filter many to many field in django


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

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

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