Handling Two Tables with Circular Foreign Keys
Two database design and insertion strategies for tables whose primary keys also form circular foreign-key references.
I encountered this question in an interview:
How should you handle two tables whose primary keys are foreign keys to each other?
Option 1
This approach is suitable when working directly in the database:
set @@foreign_key_checks=OFFOption 2
A foreign key may be null. When using an ORM, allow the relevant foreign-key fields to be null. Save one model first with a null foreign key, save the other model, then update the first model’s foreign key.
For example, in Django:
from django.db import models
class Action(models.Model): step = models.ForeignKey('Step', related_name='step', null=True, blank=True)
class Step(models.Model): action = models.ForeignKey('Action', related_name='action', null=True, blank=True)Save the objects in this order:
a = Action(step_id=None)a.save()
s = Step(action_id=a.id)s.save()
a.step_id = s.ida.save()