Reputation: 154454
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:
Owner.save
: how should the situation when commit=False
be handled?OneToOneField
from Pet
to Owner
is undesirable, as it will result in a less sensible database schema.Upvotes: 2
Views: 2651
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