是否有可能将`raw-sql`重写为`django-orm`?

时间:2017-04-04 12:38:44

标签: mysql django django-queryset django-orm

我需要将raw-sql重新写入django-orm。但不幸的是我不能这样做。有人有想法吗?:

HttcOrder.objects.raw('''SELECT httc_order.id, httc_order.price, httc_order.quantity,
                                        SUM(markedskraft_trade.qty) as positions_quantity
                                        FROM httc_order left outer join markedskraft_trade on httc_order.id = markedskraft_trade.httc_order_id
                                        WHERE httc_order.order_status in ('new', 'pending', 'confirmed')
                                        and httc_order.mk_contract_id = %s
                                        group by httc_order.id
                                        having positions_quantity is NULL or quantity - positions_quantity > 0
                                        order by httc_order.price desc''', [contract.id])

模型示例:

httc:

class Order(models.Model):
    quantity = models.IntegerField(verbose_name=_('Qty'))
    order_status = models.CharField(max_length=10, choices=ORDER_STATUSES, default=NEW)
    price = models.IntegerField(verbose_name=_('Prc'))
    mk_contract = models.ForeignKey(
        Contract, related_name='httc_orders', verbose_name=_('Markedskraft contract')
    )
    ....

markedskraft:

   class Trade(models.Model):
       order_id = models.IntegerField(blank=True, null=True, db_index=True)
       httc_order_id = models.ForeignKey(HttcOrder, blank=True, null=True, db_index=True)
       qty = models.IntegerField()
       .......

0 个答案:

没有答案