2014-11-21 69 views
0

我有一個post_save,它在創建Subscription對象後創建一個Product對象。我有實例名稱填充幾個字段,我想也傳遞一個額外的屬性。這裏是我的post_save:Django 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) 

我想爲目錄PUBLISH_DATE拉它的認購起始日期字段值。

回答

1

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) 
+0

謝謝!這正是我想要弄清楚的。 – byrdr 2014-11-21 19:02:41