Hi,
I have 5 classes:
class Event(models.Model):
class EventType(models.IntegerChoices):
CREATE = 1
UNASSIGN = 2
ASSIGN = 3
CANCEL = 4
type = models.SmallIntegerField(choices=EventType.choices)
group = models.ForeignKey(
Group,
on_delete=models.PROTECT,
)
assignee= models.ForeignKey(
Assignee,
on_delete=models.PROTECT,
)
class Group(models.Model):
date = models.DateField()
class Deal(models.Model):
product = models.ForeignKey(
Product,
on_delete=models.PROTECT,
verbose_name="The underlying product with unit, exchange, size, period and date"
)
group = models.ForeignKey(
Group,
on_delete=models.PROTECT,
)
quantity = models.IntegerField()
class Product(models.Model):
name = models.CharField()
class Assignee(models.Model):
name = models.CharField()
I am trying to get a sum of quantities per assignee per product, where the latest event is not cancelled The assignee is calculated by the latest event for a given group.
I can achieve this relatively easily in raw SQL using a group by function (I can add this here if that’s helpful). I know how to get a sum on one or the other, using an annotate. Here would be example just per product:
latest_events = Event.objects.order_by(
"group_id",
"-id"
).distinct(
"group_id"
)
valid_events= Event.objects.exclude(
type=Event.EventType.CANCEL,
)filter(
id__in=Subquery(latest_events.values("id"))
)
Product.objects.annotate(
summed_quantity = Sum(
"quantity",
filter=Q(
deal__group_id__in=Subquery(
valid_events.values("group_id")
)
)
)
)
How would I get this subdivided by assignee and product instead? Any suggestions would be appreciated, I haven’t managed to find anything similar in the documentation.