Search code examples
djangodjango-modelsdjango-signals

Django OneToOneField and signals


I have a model called DeviceStatus which has a OneToOne relationship with another model called Device. I want to get the id passed to the DeviceStatus object before saving, but all I get is a ForwardManyToOneDescriptor object.

class DeviceStatus(TimeStampedModel):
    device = models.OneToOneField(Device)
    # other fields

    def __unicode__(self):
        return u'{}'.format(self.device)

    def copy_to_archive(**kwargs):
        print DeviceStatus.device

    pre_save.connect(copy_to_archive)

Can somebody guide me through how to get the Device id being passed? TIA


Solution

  • Should be instance method

    def copy_to_archive(self, **kwargs):
        print self.device
    

    Also connecting signal like this won't work. But this is different question.

    Answering comment and extending my answer in comment to post

    This what needed to be done

    class MyClass(models.Model):
        #....
        @classmethod
        def before_save(cls, sender, instance, *args, **kwargs):
            instance.test_field = "It worked"
    
    pre_save.connect(MyClass.before_save, sender=MyClass)
    

    Django 1.2: How to connect pre_save signal to class method