Django框架图书管理一对多添加操作

 

 

 

from django.db import models

# Create your models here.

class Book(models.Model):
title = models.CharField(max_length=32)
price = models.DecimalField(max_digits=8,decimal_places=2) #999999.99
pub_date = models.DateField()

# 一对多的关联字段 publish_id
publish = models.ForeignKey("Publish",on_delete=models.CASCADE,db_constraint=False)
#models.ForeignKey("Publish", 1.publish_id(默认数据库里加_id);2.关联Publish表
#制定删除该表数据的类型:级联删除
#db_constraint = False 取消外键约束

#创建外键约束语法:refference

# 多对多的关联关系
authors = models.ManyToManyField("Author",db_table="book2author")
#models.ManyToManyField("Author") Book和Author表关联
#db_table = "book2author" 自定义关联表名称

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

class Author(models.Model):
name = models.CharField(max_length=32)
age = models.IntegerField()

# 多对多的关联关系
#class Book2Author():
# book_id = models.ForeignKey("Book",on_delete=models.CASCADE)
# author_id = models.ForeignKey("Author",on_delete=models.CASCADE)


 

 

from django.shortcuts import render,HttpResponse

# Create your views here.
from .models import *
def add(request):

pub = Publish.objects.get(name="苹果出版社")
Book.objects.create(title="西游记", price=199, pub_date="2012-12-12",publish=pub)
Book.objects.create(title="水浒传", price=299, pub_date="2011-11-11", publish_id=2)

print(type(Book.id))

return HttpResponse("OK")

 

 

"""ORM URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from app01.views import add
urlpatterns = [
path('admin/', admin.site.urls),
path('add/', add),
]

项目目录(ORM):
python3 manage.py makemigrations (创建3个模型)
python3 manage.py migrate (生成4个表)

posted @ 2022-07-27 21:29  呼长喜  阅读(102)  评论(0编辑  收藏  举报