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

 

posted @ 2021-08-09 15:37  Star-Hitian  阅读(43)  评论(0编辑  收藏  举报