码迷,mamicode.com
首页 > 其他好文 > 详细

django的模型层(二)

时间:2019-11-11 18:17:14      阅读:56      评论:0      收藏:0      [点我收藏+]

标签:mod   city   出版社   book   name   self   man   git   多对多   

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的模型层(二)

标签:mod   city   出版社   book   name   self   man   git   多对多   

原文地址:https://www.cnblogs.com/augustyang/p/11837225.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!