This query should return the total sum of (quantity - qty_fulfilled)
grouped by product_id
.
I'm stuck trying to convert this postgres sql query into an ORM query, to be returned in get_queryset()
in the Admin model. Something like this.
This sql query works, but get_queryset()
method in the Admin models does not support RawQueryset
as indicated here, so this needs to be in a Queryset form.
select t1.id, t3.req_from_orders from inventory_inventory t1
left join
product_app_product t2
on t1.product_id = t2.id
left join
(
select product_id, sum(quantity) - sum(qty_fulfilled) as req_from_orders
from order_app_cartitem oac
group by oac.product_id
) t3
on t1.product_id = t3.product_id
Models:
* Inventory
* product_id (OneToOneField)
* id (UUID)
* Product
* id (UUID)
* CartItem
* id (UUID)
* product_id (ForeignKey)
* quantity (int)
* qty_fulfilled (int)
* Inventory <-> Product <-* CartItem
class Product(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
class CartItem(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True)
quantity = models.IntegerField(null=True, verbose_name="Quantity Ordered", default=0)
qty_fulfilled = models.IntegerField(default=0, verbose_name="Quantity Fulfilled", validators=[MinValueValidator(0)])
class Inventory(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
product = models.OneToOneField(Product, on_delete=models.SET_NULL, null=True)
Tried using annotate(RawSQL="<query>", params=(param,))
but params cannot take in dynamic ids.
Any help would be greatly appreciated.
Edit: Is there any way to represent this sql query as an ORM query? Added models to make testing easier.