django的模型层
Posted augustyang
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了django的模型层相关的知识,希望对你有一定的参考价值。
django的模型层(二)
一 创建模型
from django.db import models # Create your models here. class Author(models.Model): nid = models.AutoField(primary_key=True) name = models.CharField(max_length=32) age = models.IntegerField() # 一对一 authordetail = models.OneToOneField(to="AuthorDetail", to_field="nid", on_delete=models.CASCADE) def __str__(self): return self.name # 作者详情表 class AuthorDetail(models.Model): nid = models.AutoField(primary_key=True) birthday = models.DateField() telephone = models.BigIntegerField() addr = models.CharField(max_length=64) # 出版社表 class Publish(models.Model): nid = models.AutoField(primary_key=True) name = models.CharField(max_length=32) city = models.CharField(max_length=32) email = models.EmailField() def __str__(self): return self.name class Book(models.Model): nid = models.AutoField(primary_key=True) title = models.CharField(max_length=32) publishDate = models.DateField() price = models.DecimalField(max_digits=5, decimal_places=2) # 一对多关系 publish = models.ForeignKey(to="Publish",to_field="nid",on_delete=models.CASCADE) ‘‘‘ publish_id INT , FOREIGN KEY (publish_id) REFERENCES publish(id) ‘‘‘ # 多对多 authors = models.ManyToManyField(to="Author") ‘‘‘ CREATE TABLE book_authors( id INT PRIMARY KEY auto_increment , book_id INT , author_id INT , FOREIGN KEY (book_id) REFERENCES book(id), FOREIGN KEY (author_id) REFERENCES author(id) ) ‘‘‘ # class Book2Author(models.Model): # # nid = models.AutoField(primary_key=True) # book=models.ForeignKey(to="Book") # author=models.ForeignKey(to="Author") def __str__(self): return self.title
二 添加表记录
1 一对多
2 多对多
三 基于对象的跨表查询
1 一对多
2 一对一
3 多对多
四 基于双下划线的跨表查询
以上是关于django的模型层的主要内容,如果未能解决你的问题,请参考以下文章