A Many-to-One relationship models scenarios where multiple child records reference a single parent record (for example, multiple blog posts belonging to one author). In Django ORM, Many-to-One fields are created using models.ForeignKey().
Django ForeignKey Models & Optimized Query Example
from django.db import models
from django.contrib.auth.models import User
class Category(models.Model):
name = models.CharField(max_length=100)
slug = models.SlugField(unique=True)
class Article(models.Model):
title = models.CharField(max_length=200)
author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='articles')
category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True, related_name='articles')
# Optimized Query Example (Prevents N+1 database queries using select_related)
def get_articles_with_authors():
return Article.objects.select_related('author', 'category').all()
Comments and corrections