【发布时间】:2018-09-14 15:55:31
【问题描述】:
我有两个模型,A 和 B。每当我在 model B 中插入另一个值时,我想增加 model A 的一个字段中的值。我正在使用 post_save 信号,但我不断收到此错误“'update_fields' is an invalid keyword argument for this function”
下面是我的代码,谢谢你的帮助。
class Sales(models.Model):
id = models.AutoField(primary_key=True)
order_details = models.ForeignKey(GeneralConsulting)
medication_name_id = models.ForeignKey(Medication_List)
dosage = models.CharField(max_length=10, blank=True)
duration = models.CharField(max_length=10, blank=True)
quantity = models.IntegerField(default=0)
...
@receiver(signals.post_save, sender=Sales)
class Product(models.Model):
id = models.AutoField(primary_key=True)
product_name = models.ForeignKey(Medication_List)
description = models.TextField(blank=True)
supplier = models.ManyToManyField(Supplier, blank=True)
expiration_date = models.DateField(blank=False, null=True )
...
quantity_sold = models.IntegerField(default=0)
minimum_stock_level = models.IntegerField(default=1)
def add_on(self, sender, created, instance, update_fields, **kwargs ):
if created or update_fields is 'quantity':
b = Product.objects.get(product_name_id=instance.id)
if b.quantity_sold + instance.quantity <= b.initial_qty:
b.quantity_sold = b.quantity_sold + instance.quantity
b.save(update_fields=['quantity_sold'])
所以我想做的就是增加 Product.quantity_sold 字段中的值 每当添加新的销售时。
请帮助,我对 django 信号很陌生。有一个更好的方法吗?谢谢
【问题讨论】:
-
你能改变
@receiver(signals.post_save, sender=Sales)=>@receiver(models.signals.post_save, sender=Sales)吗? -
嗯,运气不好。再次弹出同样的错误
标签: python django django-models relational-database django-signals