David Wolever
David Wolever

Reputation: 154454

Django: save a OneToOneField automatically from *related* model?

Consider two models (ignoring the obvious logical issues):

class Owner(m.Model):
    id = m.IntegerField(primary_key=True)

class Pet(m.Model):
    owner = m.OneToOneField(Owner, related_name="pet", primary_key=True)

When creating a new Owner, is it possible to have their .pet saved automatically?

Currently, this is what happens:

>>> o = Owner()
>>> o.pet = Pet()
>>> o.save()
>>> o.id
42
>>> o.pet.id
None
>>> o.pet.owner_id
None
>>> o.pet.owner == o
True

But I would like (and expect?) that o.pet would be saved in the process of saving o.

Notes:

Upvotes: 2

Views: 2651

Answers (1)

K Z
K Z

Reputation: 30453

If I understand the question correctly, you can use django.db.models.signals.post_save to achieve the desired outcome without overriding Owner.save():

from django.db.models.signals import post_save

post_save.connect(save_pet_handler, sender=Owner, dispatch_uid="my_unique_identifier")

def save_pet_handler(sender, instance, created, **kwargs):
    ...

Once o.save() is called, a signal will be fired to call save_pet_handler, where you can then have o.pet saved or updated, depends on the boolean value of created.

Upvotes: 2

Related Questions