Sobes.tech
Junior — Middle

How can you access related models or fields through Django ORM?

sobes.tech AI

Answer from AI

In Django ORM, access to related models is done through relation fields such as ForeignKey, OneToOneField, and ManyToManyField.

  • To access a related object via ForeignKey or OneToOneField, use the attribute with the field's name:
class Author(models.Model):
    name = models.CharField(max_length=100)

class Book(models.Model):
    author = models.ForeignKey(Author, on_delete=models.CASCADE)
    title = models.CharField(max_length=100)

book = Book.objects.get(id=1)
author = book.author  # access to the related Author object
  • For reverse access (from the parent model to related objects), use the attribute with the suffix _set by default or related_name if specified:
author = Author.objects.get(id=1)
books = author.book_set.all()  # all books of the author
  • For ManyToManyField, access to related objects is also through the field attribute:
class Student(models.Model):
    name = models.CharField(max_length=100)

class Course(models.Model):
    students = models.ManyToManyField(Student)

course = Course.objects.get(id=1)
students = course.students.all()  # all students of the course

Thus, access to related models in Django ORM is done through attributes corresponding to relation fields and QuerySet methods for working with multiple relations.