English 中文(简体)
Django的有条件说明
原标题:Conditional annotations in Django

我只是简单的要求(并非简单执行),并概括了如何实现这一要求,而不必对 d进行多次打击,在盘问时没有<代码>.extra()。

Task:
  name = xxx
  status = models.IntegerField(choices=some_choices)
  project = ForeignKey(Project)

Project:
  name = xxx
  code = xxx

Projects contain Tasks which got various statuses. (Assume status=3 is Completed) Now, I want to list out all projects with their total tasks and completed tasks, like below

  1. Project 1, total_tasks=5, completed_tasks=2
  2. Project 1, total_tasks=2, completed_tasks=1

我能够拿到全部的“信使”,但还没有完成——信使,因为它需要说明条件。 是否有办法?

最佳回答

I don t know if it will help, but you can write your own custom annotation objects. I ve just done it though without the conditional part. I based my solution on this link: http://www.voteruniverse.com/Members/jlantz/blog/conditional-aggregates-in-django

但却没有使用这个例子。 相反,我审视了集权法,并扩大了苏姆和大标本身。

问题回答

如果你不考虑更多的询问,你可以提出两个问题,而不是一个问题。 第一种办法可以让你获得全部票价,第二种可打上<条码>tasks_status,从而使你获得完整的票价。

from django.db.models import Count
all_projects = Project.objects.all()
total_counts = all_projects.annotate(count = Count( tasks ))
completed_counts = all_projects.filter(tasks_status = 3).annotate(count = Count( tasks ))




相关问题
How to get two random records with Django

How do I get two distinct random records using Django? I ve seen questions about how to get one but I need to get two random records and they must differ.

Moving (very old) Zope/Plone Site to Django

I am ask to move data from a (now offline) site driven by Plone to a new Django site. These are the version informations I have: Zope Version (unreleased version, python 2.1.3 ) Python Version 2.1....

Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

Flexible pagination in Django

I d like to implement pagination such that I can allow the user to choose the number of records per page such as 10, 25, 50 etc. How should I go about this? Is there an app I can add onto my project ...

is it convenient to urlencode all next parameters? - django

While writing code, it is pretty common to request a page with an appended "next" query string argument. For instance, in the following template code next points back to the page the user is on: &...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

热门标签