无法使用post_save信号将产品sku保存到django模型

时间:2015-12-18 08:58:05

标签: django django-models

您好我正在尝试将产品sku保存到django模型但它不会保存任何内容并且无声地失败

这是models.py

class Product(models.Model):
    brand = models.ForeignKey(Brand , related_name='products')
    category = models.ForeignKey('Category', verbose_name='categories', related_name='products' , default='')
    title = models.CharField(max_length=500)
    SKU = models.CharField(max_length=100 , blank=True ,  unique=True)

def product_post_save_receiver(sender,instance,*args,**kwargs):
    if instance.SKU is None:
        var1 = instance.title[:3]
        var2 = instance.brand.title[:3]
        var3 = var1+var2
        instance.SKU = var3
        instance.save()

post_save.connect(product_post_save_receiver,sender=Product)

我该怎么做才能解决上述问题
提前谢谢

1 个答案:

答案 0 :(得分:0)

你尝试过这样的事吗?

@receiver(post_save, sender=Product)
def product_post_save_receiver(sender,instance,**kwargs):
if instance.SKU is None:
    var1 = instance.title[:3]
    var2 = instance.brand.title[:3]
    var3 = var1+var2
    instance.SKU = var3
    instance.save()