第四章、Django之模型层---创建模型

目录

第四章、Django之模型层---创建模型

一、写models.py

from django.db import models

# Create your models here.
"""
你在写orm语句的时候 跟你写sql语句一样
不要想着一次性写完
写一点查一点看一点
"""



class Book(models.Model):
    title = models.CharField(max_length=32)
    price = models.DecimalField(max_digits=8,decimal_places=2)
    publish_date = models.DateField(auto_now_add=True)

    # 书籍与出版社 是一对多关系
    publish = models.ForeignKey(to='Publish')
    # 书籍与作者 是多对多
    authors = models.ManyToManyField(to='Author')
    """
    authors虚拟字段
        1.告诉orm自动帮你创建第三张关系表
        2.orm查询的时候  能够帮助你更加方便的查询
    """

    def __str__(self):
        return self.title


class Publish(models.Model):
    name = models.CharField(max_length=32)
    addr = models.CharField(max_length=64)

    def __str__(self):
        return self.name
    """return返回的数据必须是字符串类型"""



class Author(models.Model):
    name = models.CharField(max_length=32)
    age = models.IntegerField()
    # author_detail = models.ForeignKey(unique=True,to='AuthorDetail')
    author_detail = models.OneToOneField(to='AuthorDetail')


    def __str__(self):
        return self.name

class AuthorDetail(models.Model):
    phone = models.BigIntegerField()
    addr = models.CharField(max_length=64)

    def __str__(self):
        return self.addr

猜你喜欢

转载自www.cnblogs.com/demiao/p/11735221.html