• Django多表操作关系创建


     多表操作:以book,publish, author为例

      一对多:一旦确定一对多的关系,在多的一方(book)创建关联字段publish_id

      多对多:一旦确定多对多的关系,创建第三张表,比如Author2Book表,字段分别是id,Book_id, Author_id

      一对一:两张表其实就是一张表,在任意一张表创建关联字段

    from django.db import models
    
    # Create your models here.

    #不用创建ID,Django自动创建主键
    class Book(models.Model): title=models.CharField(max_length=32,unique=True) price=models.DecimalField(max_digits=8,decimal_places=2,null=True)# 999999.99 pub_date=models.DateField() publish=models.ForeignKey(to="Publish",to_field="id",on_delete=models.CASCADE)
    django2.0需要写cascade authors
    =models.ManyToManyField(to="Author"
    )
      这里authors只是属性,不是字段,为了创建多对多关联表
    def __str__(self):
    return self.title class Publish(models.Model): name=models.CharField(max_length=32) email=models.CharField(max_length=32) addr=models.CharField(max_length=32) class Author(models.Model): name=models.CharField(max_length=32) age=models.IntegerField() 这个不用# ad=models.ForeignKey(to="AuthorDetail",to_field="id",on_delete=models.CASCADE,unique=True) ad=models.OneToOneField(to="AuthorDetail",to_field="id",on_delete=models.CASCADE,)
      用这个
    class AuthorDetail(models.Model): gf=models.CharField(max_length=32) tel=models.CharField(max_length=32)

    然后使用tools里面的run manage.py task 输入makemigrations和migrate生成数据库

    就创建完多对多表啦~

  • 相关阅读:
    CF140CNew Year Snowmen
    ZR10.1青岛集训三地联考
    CF1228——记一次和紫名失之交臂的CF
    CF1220
    codeforce 382 div2 E —— 树状dp
    codeforce 381 div2
    codeforce 380(div.2)
    Bishops Alliance—— 最大上升子序列
    codeforce 379(div.2)
    模板——BigInteger
  • 原文地址:https://www.cnblogs.com/kateli/p/9240335.html
Copyright © 2020-2023  润新知