When creating two instances of a model and connecting them using a OneToOneField, the connection gets created and saved automatically at object creation:
from django.db import models
class MyModel(models.Model):
name = models.CharField(primary_key=True, max_length=255)
next = models.OneToOneField('self', on_delete=models.SET_NULL, related_name='prev', null=True, blank=True)
>>> m2 = MyModel.objects.create(name="2")
>>> m1 = MyModel.objects.create(name="1", next=m2)
>>> m2.prev
<MyModel: 1>
>>> m2.refresh_from_db()
>>> m2.prev
<MyModel: 2>
However, when creating the same connection but using the reverse field, the creation is also done automatically but not the save.
>>> m1 = MyModel.objects.create(name="1")
>>> m2 = MyModel.objects.create(name="2", prev=m1)
>>> m1.next
<MyModel: 2>
>>> m1.refresh_from_db()
>>> m1.next
Note that the last statement doesn't print anything since it returns None
How can I have it always save the relation when created using the reverse field without having to manually use .save()
each time?