What are Django model relationships in depth?
Why Interviewers Ask This
This question targets practical, hands-on experience with Django. Interviewers want to see if you've worked with these concepts in real projects, not just read about them. Strong answers include concrete examples.
Answer
Django ORM supports three types of model relationships: ForeignKey (Many-to-One): class Article(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE, related_name="articles") category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True). on_delete options: CASCADE (delete children), PROTECT (prevent deletion if children exist), SET_NULL (set FK to null), SET_DEFAULT, DO_NOTHING. Access: article.author (forward), user.articles.all() (reverse via related_name). ManyToManyField: class Article(models.Model): tags = models.ManyToManyField(Tag, blank=True, through="ArticleTag"). Through model (extra fields on the relationship): class ArticleTag(models.Model): article = models.ForeignKey(Article, on_delete=models.CASCADE) tag = models.ForeignKey(Tag, on_delete=models.CASCADE) created_by = models.ForeignKey(User, on_delete=models.CASCADE) added_at = models.DateTimeField(auto_now_add=True). Access: article.tags.add(tag); article.tags.remove(tag); article.tags.set([t1, t2]); article.tags.all(); tag.article_set.all(). OneToOneField: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="profile"). Like ForeignKey but enforces uniqueness — only one Profile per User. Access: user.profile (direct, no _set). Self-referential: parent = models.ForeignKey("self", on_delete=models.CASCADE, null=True, blank=True, related_name="children"). Generic relations: use ContentType for polymorphic FK — point to any model. from django.contrib.contenttypes.fields import GenericForeignKey.
Pro Tip
If you're unsure about a detail, say so honestly and explain your reasoning. Interviewers respect candidates who can think through uncertainty rather than bluffing.
Previous
What is Django DRF authentication and permissions?
Next
What is Django Celery for background tasks?