在覆盖模型保存方法的同时,如何使用cursor.execute(“ UPDATE ...”更新另一个模型。
我有2个模型
class Medication_List(models.Model):
id = models.AutoField(primary_key=True)
medication_name=models.CharField(max_length=250, blank=True, editable=True)
medications_category = models.ForeignKey(Medication_Category,on_delete=models.CASCADE, blank=False, default=1)
stock = models.DecimalField('Current Stock Level', max_digits=10,decimal_places=2, blank=True, default=0.00)
class Medications_Bridge(models.Model):
id = models.AutoField(primary_key=True)
order_details =models.ForeignKey(GeneralConsulting, on_delete=models.CASCADE)
medication_name_id = models.ForeignKey(Medication_List, on_delete=models.CASCADE)
def save(self, *args, **kwargs):
quantity_sold = Medications_Bridge.objects.raw("SELECT *,..... )
.....
quantity_received = New_stock_purchases.objects.raw("SELECT *,.....)
for e in quantity_sold:
if e.total_quantity_sold == None:
return 0
else:
return e.total_quantity_sold
for r in quantity_received:
if r.total_quantity_received == None:
return 0
else:
return r.total_quantity_received
current_stock = r.total_quantity_received - e.total_quantity_sold
cursor.execute("UPDATE medication_productsapp_medication_list SET stock = %s WHERE id = %s" % (current_stock, self.medication_name_id.id))
transaction.set_dirty()
transaction.commit()
#i already tried transaction.commit_unless_managed() but it didn't work
super(Medications_Bridge, self).save(*args, **kwargs)
当我保存一条记录时,我的光标功能没有任何反应。它不会更新其他模型的记录。
在django中有可能发生这种事吗?还是我想念一些东西?
我知道我可以使用信号,但是我有一个循环导入问题,这限制了我使用信号的能力。 @receiver装饰器不断给我一个错误,因为Medications_Bridge(models.Model)已经导入了Medication_List(models.Model)。
任何帮助将不胜感激。