27
How do I create ForeignKey, OneToOne, and ManyToMany relationships?
Loading...
Q&A · Answered
How do I create ForeignKey, OneToOne, and ManyToMany relationships?
Accepted answer
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)Say what you tried, not only what worked — the next person needs the reasoning. Code goes in a fenced block.