Django中的Post_save信号实现

时间:2014-04-10 09:32:58

标签: django django-signals

我有这样的模特:

class Devices(models.Model):
        name = models.CharField(max_length=255, blank=True)
        uniqueid = models.CharField(db_column='uniqueid'.lower(), max_length=255, blank=True) # Field name made lowercase.
        latestposition = models.ForeignKey('Positions', db_column='latestPosition_id'.lower(), blank=True, null=True) # Field name made lowercase.
        class Meta:
            db_table = 'devices'
            verbose_name = 'Devices'
            verbose_name_plural = verbose_name

        def __unicode__(self):
            return '%s' %(self.name)

        # Call the signal to create user device when the device is created.
        dispatcher.connect(save_user_device, signal=post_save, sender=Devices)


    class UsersDevices(models.Model):
        user = models.ForeignKey(settings.AUTH_USER_MODEL)
        devices = models.ForeignKey('Devices')
        class Meta:
            db_table = 'users_devices'
            verbose_name = 'User Devices'
            verbose_name_plural = verbose_name

        def __unicode__(self):
            return '%s %s' %(self.user, self.devices)

创建设备后,我想创建用户设备。 user中的UsersDevices字段将在创建设备的用户中签名,devices将是刚刚创建的设备。

def save_user_device(sender, instance, **kwargs):
    ## Problem is here
    instance.UsersDevices.create(   )

如何使用此信号与UsersDevicesuser instance

创建device instance

2 个答案:

答案 0 :(得分:0)

在这种情况下,你真的不需要信号。覆盖模型的save()方法:

def save(self, *args, **kwargs):

    # Call the original save function to actually save the model:
    super(Devices, self).save(*args, **kwargs)

    # Now this model is saved, so we can create the UsersDevices
    UserDevices(user=get_user_from_somewhere(), devices=self).save()

有关覆盖save()方法的详细信息,请参阅文档:
https://docs.djangoproject.com/en/1.7/topics/db/models/#overriding-model-methods

答案 1 :(得分:0)

最好为此目的重新定义Devices模型的save方法。但是如果你想使用信号,可以这样做:

def save_user_device(sender, instance, **kwargs):
    ## Problem is here
    UsersDevices.create(devices=instance, user=instance.user)

在这种情况下,您必须将“用户”字段添加到“设备模型”。

小提示:你应该单独给模特命名,复数名称是不好的风格。