Making a field both foreign and primary key in Django

39 Views Asked by At

I have a database and in one of the tables, a field should both be a primary and a foreign key. I am new to Django, and I couldn't find an example implementation.

I appreciate all the help, Didem

I tried looking the documentation or some example repos but didn't see anything

1

There are 1 best solutions below

3
willeM_ Van Onsem On

Since a primary key is always unique, the ForeignKey is then a OneToOneField [Django-doc], so:

class Foo(models.Model):
    pass


class Bar(models.Model):
    foo = models.OneToOneField(Foo, primary_key=True, on_delete=models.CASCADE)

this is also how Django emulates inheritance. Indeed, with concrete inheritance it automatically adds a hidden primary key that is a OneToOneField to the parent model.