demiao

第四章、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

分类:

技术点:

相关文章:

  • 2022-03-01
  • 2021-12-07
  • 2021-11-27
  • 2021-11-16
  • 2021-06-15
  • 2021-08-03
猜你喜欢
  • 2022-12-23
  • 2021-09-11
  • 2021-08-31
  • 2021-04-05
  • 2022-12-23
  • 2019-01-02
相关资源
相似解决方案