Skip to content

Instantly share code, notes, and snippets.

@Ingco
Last active March 16, 2020 08:21
Show Gist options
  • Save Ingco/979eae00766ff52a712833c6e51e1c56 to your computer and use it in GitHub Desktop.
Save Ingco/979eae00766ff52a712833c6e51e1c56 to your computer and use it in GitHub Desktop.
def get_jobs_queryset(self) -> QuerySet:
"""
Get QuerySet from production.Job (for subquery in ProductionOrderJob queryset)
:return: QuerySet
"""
return apps.get_model("production.Job").objects.filter(
(
Q(version_end_date__gt=OuterRef("production_order__created_at"))
| Q(version_end_date__isnull=True)
)
& Q(version_start_date__lte=OuterRef("production_order__created_at"))
& Q(identity=OuterRef("production_job__identity"))
)
def get_jobs_subquery_with_price(self) -> dict:
"""Get 'price' values from versioned ProductionOrderJob's queryset"""
return self.get_jobs_queryset().values("price")
def get_orders_with_prefetch(self, year: int, month: int):
"""TODO Main"""
# Conditions for count ProductionOrderJob's for each ProductionOrder's
created_jobs_count_case = Case(
When(
Q(
poj_productionorder__created_at__month=month,
poj_productionorder__created_at__year=year,
poj_productionorder__finish_at__isnull=True,
)
| Q(
poj_productionorder__finish_at__month=month,
poj_productionorder__finish_at__year=year,
),
then=1,
),
output_field=IntegerField(),
)
#
finished_jobs_cost_subquery = (
apps.get_model("production.ProductionOrderJob")
.objects_clear.select_related("production_job")
.filter(
finish_at__year=year,
finish_at__month=month,
production_order=OuterRef("id")
)
.annotate(
job_price=Subquery(
self.get_jobs_subquery_with_price(), output_field=DecimalField()
)
)
.annotate(price=Sum("job_price"))
.values("price")[:1]
)
return (
apps.get_model("production.ProductionOrder")
.objects_clear.filter(created_at__month=month, created_at__year=year,)
.annotate(
finished_jobs_count=Count(
Case(
When(
Q(
poj_productionorder__finish_at__month=month,
poj_productionorder__finish_at__year=year,
),
then=1,
)
)
),
total_jobs_count=Count("poj_productionorder"),
created_jobs_count=Count(created_jobs_count_case),
created_jobs_cost=Coalesce(
Sum("poj_productionorder__production_job__price"),
Decimal("0.00")
),
finished_jobs_cost=Coalesce(
Sum(
Subquery(finished_jobs_cost_subquery),
output_field=DecimalField()
),
Decimal("0.00")
),
)
.values(
"pk",
"finished_jobs_count",
"total_jobs_count",
"created_jobs_count",
"created_jobs_cost",
"finished_jobs_cost",
)
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment