0

Is it possible to do an annotate count on technically 2 different tables, but same FK?

Example:

queryset = ModelName.objects
.annotate(mileage_emp_count=Count('mileageclaim__user',distinct=True))
.annotate(general_emp_count=Count('expenseclaim__user', distinct=True))

For instance using this, is User A has a mileage and an expense claim, they will appear in both queries. So I will have result of 2 if i add them together.

What i need to do, is get a total of 1 unique user instead.

Is it possible without a lot of extra checks?

Spirconi
  • 164
  • 1
  • 12
  • You could start filtering on both criteria then count distinct users int eh remaining rows – Christophe Sep 22 '21 at 11:55
  • I need the whole dataset so cant per filter, and wanted to avoid extra queries if possible. So was hoping for something like this to exist, total_emp_count=Count('expenseclaim__user' OR IN 'mileageclaim__user', distinct=True) – Spirconi Sep 22 '21 at 13:13
  • When you use `count()`, anyway you create a query. So, you can use something like `df.filter(your conditions).count(what you have to count)` – Christophe Sep 22 '21 at 13:58

0 Answers0