onetoone vs foreign key django
OneToOneField and ForeignKey in Django models: ForeignKey: A ForeignKey is used to create a many-to-one relationship, where each instance of the model with the ForeignKey represents a single instance of another model. It is added to the model class as a field, with the related model as the first argument.
Example:
from django.db import models
class Author(models.Model):
name = models.CharField(max_length=100)
class Book(models.Model):
title = models.CharField(max_length=100)
author = models.ForeignKey(Author, on_delete=models.CASCADE)
OneToOneField: A OneToOneField is used to create a one-to-one relationship between two model instances. It is added to the model class as a field, with the related model as the first argument. Each instance of the model with the OneToOneField is related to exactly one instance of the related model.
Example:
from django.db import models
class Person(models.Model):
name = models.CharField(max_length=100)
class Contact(models.Model):
person = models.OneToOneField(Person, on_delete=models.CASCADE)
phone_number = models.CharField(max_length=10)