Django
Beginner
1 min read
Model Relationships and Meta Options
Example
# blog/models.py — relationships and Meta options
from django.db import models
from django.contrib.auth.models import User
class Tag(models.Model):
name = models.CharField(max_length=50, unique=True)
slug = models.SlugField(max_length=50, unique=True)
def __str__(self):
return self.name
class UserProfile(models.Model):
"""One-to-one extension of the built-in User."""
user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile')
bio = models.TextField(blank=True)
website = models.URLField(blank=True)
def __str__(self):
return f'Profile of {self.user.username}'
class Post(models.Model):
author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='posts')
tags = models.ManyToManyField(Tag, blank=True, related_name='posts')
title = models.CharField(max_length=200)
body = models.TextField()
views = models.PositiveIntegerField(default=0)
class Meta:
ordering = ['-id']
verbose_name = 'Post'
verbose_name_plural = 'Posts'
constraints = [
models.UniqueConstraint(fields=['author', 'title'], name='unique_author_title'),
]
indexes = [
models.Index(fields=['author', '-id']),
]
def __str__(self):
return self.title
# Accessing relationships
# user.posts.all() -> all posts by this user (reverse FK)
# post.tags.all() -> all tags on this post
# tag.posts.filter(...) -> all posts with this tag (reverse M2M)
# user.profile -> OneToOne reverse accessor
Related Resources
Django Reference
Complete tag & property list
Django How-To Guides
Step-by-step practical guides
Django Exercises
Practice what you've learned
More in Django