Ich habe Modelle: < /p>
Code: Select all
class ItemCategory(models.Model):
name = CharField()
class Item(models.Model):
brand = CharField()
model = CharField()
category = ForeignKey(ItemCategory)
attributes = JSONField(default=dict) # e.g {"size": 1000, "power": 250}
class StockItem(models.Model):
item = ForeignKey(Item)
stock = ForeignKey(Stock)
quantity = PositiveIntegerField()
< /code>
Diese Modelle repräsentieren einige Artikel auf Lager.class Container(models.Model):
name = CharField()
class ContainerItem(models.Model):
container = models.ForeignKey(Container)
item_category = models.ForeignKey(ItemCategory)
attributes = models.JSONField(default=dict)
quantity = models.PositiveIntegerField()
< /code>
Um die Aggregation zu verarbeiten Ich erstelle eine Ansicht: < /p>
class ContainerListView(ListView):
model = models.Container
def get_queryset(self):
items_quantity_sq = models.Item.objects.filter(
item_category=OuterRef('item_category'),
attributes__contains=OuterRef('attributes'),
).values('item_category').annotate(
total_quantity=Sum('stock_items__quantity')
).values('total_quantity')
min_available_sq = models.ContainerItem.objects.filter(
container_id=OuterRef('pk')
).annotate(
available=Coalesce(Subquery(items_quantity_sq), Value(0))
).order_by('available').values('available')[:1]
base_qs = super().get_queryset().annotate(
# Attach the minimum available quantity across all items
potential=Subquery(min_available_sq)
).prefetch_related(
Prefetch(
"items",
queryset=models.ContainerItem.objects.all()
.annotate(available=Subquery(items_quantity_sq))
.order_by("available"),
)
)
return base_qs.order_by("potential")
Code: Select all
"size": [1000, 800]