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, related_name='books')What will
author.books.count() return after creating one author and two books linked to that author?author = Author.objects.create(name='Alice') Book.objects.create(title='Book 1', author=author) Book.objects.create(title='Book 2', author=author) result = author.books.count()
The related_name='books' on the ForeignKey allows accessing all Book objects linked to an Author via author.books. Since two books are created for the author, author.books.count() returns 2.
ManyToManyField is the correct field to represent many-to-many relationships in Django. ForeignKey is one-to-many, OneToOneField is one-to-one, and CharField is just text.
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
bio = models.TextField()And this code:
profile = Profile.objects.get(user=request.user) print(profile.bio)
Sometimes this raises
Profile.DoesNotExist. Why?The DoesNotExist error means the query found no Profile linked to the user. This happens if the user has no Profile record yet.
class Publisher(models.Model):
name = models.CharField(max_length=100)
class Book(models.Model):
title = models.CharField(max_length=100)
publisher = models.ForeignKey(Publisher, on_delete=models.CASCADE)And this code:
book = Book.objects.select_related('publisher').get(id=1)
print(book.publisher.name)What does
select_related do here?select_related performs a SQL join to get related objects in one query. This avoids extra queries when accessing related fields.
class Category(models.Model):
name = models.CharField(max_length=100)
class Item(models.Model):
category = models.ForeignKey(Category, on_delete=models.CASCADE)
name = models.CharField(max_length=100)If a Category is deleted, what happens to its related Items?
on_delete=models.CASCADE means deleting the referenced object (Category) will delete all related objects (Items) automatically.
