我有一个销售模型,定义如下:
from django.db import models
class Sale(models.Model):
sale_name = models.CharField(max_length = 30)
lead_seller = models.ManyToManyField(Employee, related name = "lead")
sellers = models.ManyToManyField(Employee, related name = "sellers")
lead_share = models.DecimalField(max_digits = 4, decimal_places = 3, null = True, blank = True)
sellers_share = models.DecimalField(max_digits = 4, decimal_places = 3, null = True, blank = True)
def __str__(self):
return self.sale_name
我创建了一个前端表单,人们可以在其中注册新的销售。关于节省,我想计算每个卖家的“佣金”。例如。潜在客户获得10%,其他卖家获得5%。这个比率是恒定的,因此当更多的卖方参与一次销售时,佣金较低。我尝试了以下方法:
from django.db.models.signals import post_save
from django.dispatch import receiver
@receiver(post_save, sender=Sale, dispatch_uid="update_shares")
def update_shares(sender, instance, **kwargs):
no_leads = Sale.lead_seller.through.objects.filter(sale_id = instance.id).count()
no_sellers = Sale.sellers.through.objects.filter(sale_id = instance.id).count()
instance.lead_share = 0.1/no_leads
instance.sellers_share = 0.05/no_sellers
但是,似乎数据库查询给出了0:尝试创建新条目时遇到的错误是“零分区错误/”。关于如何顺利获取潜在客户/卖家数量的任何建议?
答案 0 :(得分:1)
如果instance
是Sale
对象,则可以执行以下操作:
no_leads = instance.lead_seller.count()
no_sellers = instance.sellers.count()
还要注意,也许在更新多对多关系时可能要更新计算变量,但是当不调用post_save
时,您将需要m2m_changed
。
from django.db.models.signals import post_save, m2m_changed
from django.dispatch import receiver
@receiver(m2m_changed, sender=Sale.lead_seller.through)
@receiver(m2m_changed, sender=Sale.sellers.through)
@receiver(post_save, sender=Sale, dispatch_uid="update_shares")
def update_shares(sender, instance, **kwargs):
# do your stuff....