Junior — Middle
Explain the purpose and use of the OneToOneField in Django ORM.
sobes.tech AI
Answer from AI
The OneToOneField in Django ORM is used to create a "one-to-one" relationship between two models. This means that each record in one model corresponds to exactly one record in the related model.
Example of usage:
from django.db import models
class User(models.Model):
username = models.CharField(max_length=100)
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
bio = models.TextField()
In this example, each User has exactly one Profile. This is convenient when you want to extend the standard user model with additional fields without modifying the user model itself.
on_delete=models.CASCADE means that when the user is deleted, the associated profile will be automatically deleted.