💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
[TOC=1,5] >[success] # ForeignKey -- 一对多 ![](https://box.kancloud.cn/757c77f50af2a5980038a2e442fcf4e5_506x189.png) >[success] # 案例 >[danger] ##### models.py 编写 ~~~ from django.db import models # Create your models here. class Book(models.Model): name = models.CharField(max_length=32) price = models.IntegerField() pub_data = models.DateField(auto_now_add=True) publish = models.ForeignKey('Publish') class Publish(models.Model): name = models.CharField(max_length=32) city = models.CharField(max_length=32) ~~~ >[danger] ##### views.py * get 请求通过查询Publish数据内容,展示select 下拉展示数据 * post 请求进行数据保存 * person 函数,用来展示数据 ~~~ from django.shortcuts import render,redirect from . import models # Create your views here. def index(request): if request.method == "GET": obj_publish = models.Publish.objects.all() return render(request,'index.html',{'publish':obj_publish}) if request.method == "POST": booke_name = request.POST.get('bookname' ,None) price = request.POST.get('price' ,None) publish_id = request.POST.get('name' ,None) print(booke_name,price,publish_id) models.Book.objects.create(name=booke_name,price=price,publish_id=publish_id) return redirect('/person.html') def person(request): if request.method == "GET": obj_book = models.Book.objects.all() return render(request, 'person.html', {'obj_book': obj_book}) ~~~ >[info] ## html >[danger] ##### index.html ~~~ <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form method="post"> {% csrf_token %} <table border="1px" cellspacing="0px"> <tr> <td>bookname</td> <td>price</td> <td>name</td> <td>操作</td> </tr> <tr> <td><input name="bookname"></td> <td><input name="price"></td> <td> <select name="name"> {% for i in publish %} <option value="{{ i.id }}">{{ i.name }}</option> {% endfor %} </select> </td> <td><input type="submit"></td> </tr> </table> </form> </body> </html> ~~~ * * * * * >[danger] ##### person.html ~~~ <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form method="post"> <table border="1px" cellspacing="0px"> <tr> <td>bookname</td> <td>price</td> <td>pud_data</td> <td>name</td> <td>city</td> <td>操作</td> </tr> <tr> {% for i in obj_book %} <td>{{ i.name }}</td> <td>{{ i.price }}</td> <td>{{ i.pub_data }}</td> <td>{{ i.publish.name }}</td> <td>{{ i.publish.city}}</td> {% endfor %} </tr> </table> </form> </body> </html> ~~~