Can't figure out a good way to filter by many to many relation.
class Scheduler(models.Model):
weekhours = models.ManyToManyField('WeekHour', related_name='schedulers')
def get_active_products_by_weekhour(self,weekhour):
return Product.objects.filter(scheduler__in=WeekHour.objects.get(hour=weekhour).schedulers.all())
class WeekHour(models.Model):
hour = models.PositiveSmallIntegerField(verbose_name='Hour in week (0 - 7*24')
Now suppose I have a list of numbers, for example:
hours = [2,4,6]
I want to find a Scheduler which has this exact set of WeekHour
objects with these hour
values.
So it returns scheduler if and only if there is some which has this weekhours set [WeekHour(hour=2),WeekHour(hour=4),WeekHour(hour=6)]
. So the number of related WeekHours must be the same as a size of the list. In this case 3.
Is this possible using Django orm and not using cycles?
EDIT:
What about this?
weekhours_set = [Weekhour.objects.get(hour=x) for x in hours]
scheduler = Scheduler.objects.filter(weekhours__exact=weekhours_set)
This returns:
TypeError: int() argument must be a string or a number, not 'list'