Skip to content

Q&A · Answered

How to create Django model relationships

asked 9 months, 1 week ago 2042 views 1 answer
27

How do I create ForeignKey, OneToOne, and ManyToMany relationships?

1 Answer

One accepted
7

Accepted answer

Not confirmed since it was written, 9 months, 1 week ago
from django.db import models

class Author(models.Model):
    name = models.CharField(max_length=100)

class Book(models.Model):
    title = models.CharField(max_length=200)
    # ForeignKey (many-to-one)
    author = models.ForeignKey(Author, on_delete=models.CASCADE)
    
    # ManyToMany
    categories = models.ManyToManyField('Category')

class Profile(models.Model):
    # OneToOne
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    bio = models.TextField()

class Category(models.Model):
    name = models.CharField(max_length=50)

Your answer

Say what you tried, not only what worked — the next person needs the reasoning. Code goes in a fenced block.

Shown beside your answer and never checked, so it cannot be a name someone already has here.

No account needed to answer. Sign in instead and it carries your name and earns reputation.