Junior — Middle
How can relationships between models be established within Django ORM?
sobes.tech AI
Answer from AI
In Django ORM, relationships between models are established using special fields that define the type of connection:
-
ForeignKey (one-to-many): Connects one record of a model to multiple records of another.
-
OneToOneField (one-to-one): Connects one record of a model to one record of another.
-
ManyToManyField (many-to-many): Allows linking multiple records of one model with multiple records of another.
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=200)
author = models.ForeignKey(Author, on_delete=models.CASCADE) # one author - many books
class Profile(models.Model):
user = models.OneToOneField('auth.User', on_delete=models.CASCADE) # one profile - one user
class Student(models.Model):
name = models.CharField(max_length=100)
courses = models.ManyToManyField('Course') # student can attend many courses
class Course(models.Model):
title = models.CharField(max_length=200)
Thus, using these fields, you can explicitly define and manage relationships between models in the database.