假设我有两个模型:
class Testmodel1():
amount = models.IntegerField(null=True)
contact = models.ForeignKey(Testmodel2)
entry_time = models.DateTimeField()
stage = choicesfiled
class Testmodel2():
name = models.CharField()
mobile_no = models.CharField()我想找出contact > 3的Testmodel1对象,它是在过去24小时的last = arrow.utcnow().shift(hours=-24).date()中创建的。
我正在应用一个查询:
n1=Testmodel1.objects.filter(entry_time__gte=last, stage=1).annotate(t_count=Count('contact')).filter(t_count__gt=3)但它似乎不起作用。因为我得到了一个空的查询集。
任何帮助都将不胜感激。
发布于 2018-01-31 21:47:53
只有部分答案。抱歉的!您的代码在我看来很好,所以我只是试图从不同的方向找到解决方案。
下面是我如何在我的一个项目中构建(某种程度上)类似的代码。
from datetime import timedelta, date
....
base_date = date.today()
start_date = base_date + timedelta(days=30)
end_date = base_date
possible_holidays = Holiday.objects.filter(
start_date__lte=start_date, end_date__gte=end_date)从那里开始,你可以做一些类似这样的事情:
if possible_holidays.contact_set.count() > 3:
pass这行得通吗?
发布于 2018-01-31 22:06:52
问题是你的多对一关系是颠倒的。此关系是父子关系,其中一个父项可以有多个子项,但子项只能有一个父项。在数据库中,此关系被存储为指向子代的父代的子代的ForeignKey字段。
在本例中,Testmodel1是父级,Testmodel2是子级(Testmodel1可以有多个由Testmodel2表示的联系人),这意味着ForeignKey字段应该属于Testmodel2,而不是Testmodel1。
class Testmodel1():
amount = models.IntegerField(null=True)
entry_time = models.DateTimeField()
stage = choicesfiled
class Testmodel2():
name = models.CharField()
mobile_no = models.ForeignKey()
parent = models.ForeignKey(Testmodel1,
related_name='contacts',
)使用此模型结构,您可以将Testmodel1的联系人引用为testmodel1.contacts.all()。您的查询应如下所示:
n1 = (Testmodel1.objects
.filter(entry_time__gte=last, stage=1)
.annotate(t_count=Count('contacts'))
.filter(t_count__gt=3)
)https://stackoverflow.com/questions/48542152
复制相似问题