我有一个post_save,它在创建Subscription对象后创建一个Product对象。我有实例名称填充几个字段,我还想传入一个额外的属性。这是我的post_save:
@receiver(post_save, sender=Subscription)
def create_product_subscription(sender, **kwargs):
subscription = Category.objects.get(name="Subscription")
if kwargs.get('created', False):
Product.objects.get_or_create(name=kwargs.get('instance'),
slug=slugify(kwargs.get('instance')),
price=44.98,
quantity='3000',
publish_date=kwargs.get('instance'), //this is where I'd like to pass an attribute of the instance
categories=subscription)
这是我的订阅模型:
class Subscription(models.Model):
name = models.CharField(max_length=200)
start_date = models.DateField()
end_date = models.DateField()
date = models.DateTimeField(auto_now_add=True, blank=True)
def __unicode__(self):
return unicode(self.start_date)
我希望Catalog Publish_Date从Subscription start_date字段中提取它的值。
答案 0 :(得分:3)
kwargs.get('instance')
会为您提供发件人对象的实例。
一旦我们拥有了实例对象,我们就可以在实例上执行点符号查找来获取属性。
kwargs.get('instance').yourattribute
或者,我们可以使用更具说明性的函数定义,并将实例和创建的变量作为位置参数包含在Django文档中,https://docs.djangoproject.com/en/dev/ref/signals/#django.db.models.signals.post_save
以下是使用位置参数的代码,例如
@receiver(post_save, sender=Subscription)
def create_product_subscription(sender, instance, created, **kwargs):
subscription = Category.objects.get(name="Subscription")
if created:
Product.objects.get_or_create(name=instance,
slug=slugify(instance),
price=44.98,
quantity='3000',
publish_date=instance.start_date, //this is where I'd like to pass an attribute of the instance
categories=subscription)