gpt4 book ai didi

python - Django:多对多关系的自定义保存方法

转载 作者:行者123 更新时间:2023-11-28 21:26:57 25 4
gpt4 key购买 nike

我需要在多对多关系上设置自定义的保存和删除方法。
我试图用“through”属性指定一个模型,但这使我的代码过于复杂,并引入了一些问题。在多对多模型上,我不需要任何额外的字段,只需要自定义保存和删除方法。
是否可以在不指定“through”属性的情况下完成此任务?
代码如下:

class Order(BaseDate):
#lots of fields
relateds = models.ManyToManyField('RelatedProduct', verbose_name=_('related products'), blank=True, related_name='order_relateds', through='OrderRelateds')
# more fields
total = CurrencyField(verbose_name=_('total'))

def calculate_total(self):
cleanses = self.cleanse.taxed_price() * self.quantity
delivery = DELIVERY_PRICE if self.delivery == 'delivery' else 0
relateds = 0
for r in self.relateds.all():
relateds = relateds + float(r.taxed_price())
total = float(cleanses) + delivery + relateds
return total

def save(self, *args, **kwargs):
self.total = '%.2f' % self.calculate_total()
super(Order, self).save(*args, **kwargs)

class OrderRelateds(models.Model):
order = models.ForeignKey(Order)
relatedproduct = models.ForeignKey(RelatedProduct, verbose_name=_('related product'))

class Meta:
verbose_name = _('Related Product')
verbose_name_plural = _('Products Related to this Order')

def __unicode__(self):
return self.relatedproduct.__unicode__()

def save(self, *args, **kwargs):
super(OrderRelateds, self).save(*args, **kwargs)
self.order.save()

def delete(self, *args, **kwargs):
super(OrderRelateds, self).delete(*args, **kwargs)
self.order.save()

如果订单中添加或删除了任何相关产品(多对多商品),我需要触发重新计算订单总价。
编辑:这是解决我问题的代码
from django.db.models.signals import m2m_changed
from django.dispatch import receiver

@receiver(m2m_changed, sender=Order.relateds.through)
def recalculate_total(sender, instance, action, **kwargs):
"""
Automatically recalculate total price of an order when a related product is added or removed
"""
if action == 'post_add':
instance.save()
if action == 'post_remove' or action == 'post_clear':
instance.save()

最佳答案

您可以在包含关系的模型上使用django的m2m_changed, pre_save/post_save, pre_delete/post_delete signals,并在那里执行相关逻辑。

关于python - Django:多对多关系的自定义保存方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11988946/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com