【问题标题】:Annotate not returning the expected results注释不返回预期结果
【发布时间】:2017-10-19 15:27:45
【问题描述】:

我这里有一个模型如下:

class Project(models.Model):
    project_id = models.CharField(max_length=10, blank=False, primary_key=True)
    title = models.CharField(max_length=128, blank=False,)
    start_date = models.DateField(null=False)
    end_date = models.DateField(null=True)
    total_amount = models.DecimalField(max_digits=10, decimal_places=2)
    raised_amount = models.DecimalField(max_digits=10, decimal_places=2)
    cause = models.ForeignKey('Cause', on_delete=models.SET('cause not set'))
    ngo_id = models.ForeignKey('NGO', on_delete=models.SET('ngo not set'))
    zip = models.IntegerField(blank = True)
    reimagine_fees=models.DecimalField(max_digits=10, decimal_places=3,default=0.05)
    person_of_contact = models.CharField(max_length = 100)
    summary = models.TextField(blank = False)
    story = models.TextField(blank = True)
    fb_description=models.CharField(max_length = 301,blank=True)
    tax_exemption_available = models.BooleanField(default=False)
    banner = models.TextField(blank=True)
    team_member_id = models.ForeignKey(Team_Member, on_delete=models.SET('team member not set'))
    project_page_desc = models.CharField(max_length=300, blank=True)

    def __str__(self):
        return self.title

我正在尝试根据资金的百分比来过滤项目对象,即raised_amounttotal_amount 的比率...我正在为此使用注释。但是,过滤器没有给出我预期的结果。我的过滤查询是:

project_list = project_list.annotate(x=F('raised_amount')/F('total_amount')).exclude(x__gte=0.8)

project_list = project_list.annotate(x=F('raised_amount')/F('total_amount')).exclude(x__lte=0.2)

project_list = project_list.annotate(x=F('raised_amount')/F('total_amount')).exclude(x__lte=1, end_date__gte=datetime.date.today())

project_list 是所有Project 对象的查询集。

在这里帮我...

【问题讨论】:

  • 你期待什么?
  • ...这与您实际得到的有什么不同?
  • 如果 project_list 是字典,你为什么要在它上面调用 annotate?您应该在 QuerySet 上调用 annotate
  • 对不起,它已经是一个查询集...错字,我的错...我已经纠正了这个问题
  • 我期待它根据我在过滤器中添加的计算显示项目显然......但在某些情况下它要么不返回任何对象,要么返回不正确的对象

标签: python django django-models annotations django-queryset


【解决方案1】:
projects = Project.objects.all() # projects is a queryset

project_list = projects.annotate(x=F('raised_amount')/F('total_amount')).exclude(x__gte=0.8)

在查询集上尝试所有注释,而不是在字典上。

【讨论】:

    猜你喜欢
    • 2016-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多