Django多表操作
阿新 • • 發佈:2018-06-28
輸入 ask __str__ models field pla 多對多 model class
多表操作:以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生成數據庫
就創建完多對多表啦~
Django多表操作