按多种关系过滤对象

时间:2016-12-11 18:09:09

标签: python django django-models many-to-many django-orm

无法找出按多对多关系过滤的好方法。

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

现在假设我有一个数字列表,例如:

hours = [2,4,6]

我想找到一个包含这些WeekHourhour[WeekHour(hour=2),WeekHour(hour=4),WeekHour(hour=6)]个对象的调度程序。

因此,当且仅当有一些周末时间设置为weekhours_set = [Weekhour.objects.get(hour=x) for x in hours] scheduler = Scheduler.objects.filter(weekhours__exact=weekhours_set) 时才会返回调度程序。因此,相关WeekHours的数量必须与列表的大小相同。在这种情况下3。

这是否可以使用Django orm而不使用循环?

编辑:

这个怎么样?

rect

返回:

  

TypeError:int()参数必须是字符串或数字,而不是'list'

1 个答案:

答案 0 :(得分:0)

__exact期望与字段类型相同的类型。

您应该考虑使用__in,然后将operator.and_上的Q表达式链接到过滤 完全对象,该对象与ids的关联所有相关的对象:

import operator
from django.db.models import Q

weekhours_set = Weekhour.objects.filter(hour__in=hours).values_list('id', flat=True)
schedulers = Scheduler.objects.filter(reduce(operator.and_, [Q(weekhours__id=id) for id in weekhours_set]))
相关问题