Djnago models 一对多、多对多
一对多,在多的class 中创建 ForeignKey (外键)
class Publisher(models.Model): name = models.CharField(max_length=32, verbose_name='出版社名称') def __str__(self): return self.name class Meta: verbose_name = "name" verbose_name_plural = verbose_name class Book(models.Model): name = models.CharField(max_length=32, verbose_name='书名') pub = models.ForeignKey('Publisher', on_delete=models.CASCADE,related_name='books', related_query_name='book')
多对多中,在哪个表中创建都可以
from django.db import models class Publisher(models.Model): name = models.CharField(max_length=32, verbose_name='出版社名称') def __str__(self): return self.name class Meta: verbose_name = "name" verbose_name_plural = verbose_name class Book(models.Model): name = models.CharField(max_length=32, verbose_name='书名') pub = models.ForeignKey('Publisher', on_delete=models.CASCADE,related_name='books', related_query_name='book') def __str__(self): return self.name class Meta: verbose_name = 'name' verbose_name_plural = verbose_name class Author(models.Model): name = models.CharField(max_length=32, verbose_name='姓名') books = models.ManyToManyField('Book') def __str__(self): return self.name class Meta: verbose_name = "name" verbose_name_plural = verbose_name
本文来自博客园, 作者:Star-Hitian, 转载请注明原文链接:https://www.cnblogs.com/Star-Haitian/p/15118969.html