When you create two instances of the model and connect them using OneToOneField, the connection is created and saved automatically when the object is created:
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 opposite field, the creation is also performed automatically, but is not saved.
>>> 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 does not print anything, as it returns None
How can I always keep this relation when creating using the inverse field without having to manually use it .save()
every time?