我在Django项目中有3个模型:
class Hardware(models.Model):
inventory_number = models.IntegerField(unique=True,)
class Subdivision(models.Model):
name = models.CharField(max_length=50,)
class Relocation(models.Model):
hardware = models.ForeignKey('Hardware',)
subdivision = models.ForeignKey('Subdivision',)
relocation_date = models.DateField(verbose_name='Relocation Date', default=date.today())
表' Hardware_Relocation'例如:
id hardware subdivision relocation_date
1 1 1 01.01.2009
2 1 2 01.01.2010
3 1 1 01.01.2011
4 1 3 01.01.2012
5 1 3 01.01.2013
6 1 3 01.01.2014
7 1 3 01.01.2015 # Now hardware 1 located in subdivision 3 because relocation_date is max
我想编写一个过滤器,以便在今天的细分中找到硬件。
我正在尝试编写过滤器:
subdivision = Subdivision.objects.get(pk=1)
hardware_list = Hardware.objects.annotate(relocation__relocation_date=Max('relocation__relocation_date')).filter(relocation__subdivision = subdivision)
现在 hardware_list 包含硬件 1,但它是错误的(因为现在硬件 1 细分 3) 。 在此示例中, hardware_list 必须无。
以下代码运行错误( hardware_list 包含硬件1,细分1)。
limit_date = datetime.datetime.now()
q1 = Hardware.objects.filter(relocation__subdivision=subdivision, relocation__relocation_date__lte=limit_date)
q2 = q1.exclude(~Q(relocation__relocation_date__gt=F('relocation__relocation_date')), ~Q(relocation__subdivision=subdivision))
hardware_list = q2.distinct()
也许更好地使用SQL?
答案 0 :(得分:1)
这可能有用......
getline
这个想法是,给我所有在限制日期之前已经重新定位到目标部门的硬件,之后不会被重新安置到其他部门。