码迷,mamicode.com
首页 > 编程语言 > 详细

Python学习之路—2018/6/26

时间:2018-06-26 23:46:08      阅读:211      评论:0      收藏:0      [点我收藏+]

标签:bubuko   inf   from   djang   app   date   name   字段   S3   

Python学习之路—2018/6/26

1.ORM

单表操作

删除与修改记录

>>> ret = Book.objects.filter(title="go").delete()
(1, {‘app01.Book‘: 1})
>>> Book.objects.filter(price=115).update(price=120)

技术分享图片

技术分享图片

多表操作

创建模型

一对一

models.OneToOneField(to="表名", on_delete=models.CASCADE)

一对多

models.ForeignKey(to="表名", to_field="字段名", on_delete=models.CASCADE)

多对多

models.ManyToManyField(to="表名")

models.py

from django.db import models


class Author(models.Model):
    nid = models.AutoField(primary_key=True)
    name = models.CharField(max_length=32)
    age = models.IntegerField()
    # 与AuthorDetail建立一对一关系
    author_detail = models.OneToOneField(to="AuthorDetail", on_delete=models.CASCADE)


class AuthorDetail(models.Model):
    aid = models.AutoField(primary_key=True)
    birthday = models.DateField()
    telephone = models.BigIntegerField()
    addr = models.CharField(max_length=64)


class Publish(models.Model):
    pid = models.AutoField(primary_key=True)
    name = models.CharField(max_length=32)
    city = models.CharField(max_length=32)
    email = models.EmailField()


class Book(models.Model):
    bid = models.AutoField(primary_key=True)
    title = models.CharField(max_length=32)
    publishDate = models.DateField()
    price = models.DecimalField(max_digits=5, decimal_places=2)

    # 与Publish建立一对多关系,外键字段建立在多的一方
    publish = models.ForeignKey(to="Publish", to_field="pid", on_delete=models.CASCADE)
    """
        publish_id INT,
        FOREIGN KEY(publish_id) REFERENCES publish(pid)
    """

    # 与Author建立多对多关系
    authors = models.ManyToManyField(to="Author")
    """
        CREATE TABLE book_author(
            id INT PRIMARY KEY AUTO_INCREMENT,
            book_id INT,
            author_id INT,
            FOREIGN KEY(book_id) REFERENCES Book(bid),
            FOREIGN KEY(author_id) REFERENCES Author(nid),
        )
    """

运行结果:

技术分享图片

技术分享图片

技术分享图片

技术分享图片

技术分享图片

注意:

  • on_delete = models.CASCADE在使用一对以及一对多时需要用到
  • 外键字段会自动添加_id,比如publish = models.ForeignKey()执行后生成publish_id
  • 需要在settings.py中配置app01

添加记录

一对多

Book.objects.create(title="坏蛋是怎样炼成的", publishDate="2017-01-02", price=125, publish_id=1)

运行结果:

技术分享图片

>>> book = Book.objects.get(bid=1)
>>> print(book.bid)
1
>>>print(book.title)
坏蛋是怎样炼成的
>>> print(book.publishDate)
2017-01-02
>>> print(book.price)
125.00
>>> print(book.publish)
Publish object (1)
>>> print(book.publish.name)
中国城市出版社
>>> print(book.publish.email)
qianchuaner@sina.com

Python学习之路—2018/6/26

标签:bubuko   inf   from   djang   app   date   name   字段   S3   

原文地址:https://www.cnblogs.com/ExBurner/p/9231652.html

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