Skip to content
Back to posts

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=OFF

Option 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.id
a.save()

Originally published on SegmentFault.

Copyright notice

Unless otherwise stated, quietin owns the copyright in all articles. All rights reserved. Except as permitted by law or with prior written permission, reproduction or republication, in whole or in part, is prohibited. Permitted quotations must credit the author and link to the original article.