数据库映射关系:一对一、一对多、多对多
1、一对一案例:账号和联系人
Model
from django.db import models
账号
class Account(models.Model):
username = models.CharField(max_length=20, null=True)
password = models.CharField(max_length=20)
register = models.DateField(auto_now_add=True)联系人
class Connect(models.Model):
account = models.OneToOneField("Account", on_delete="CASCADE")
address = models.CharField(max_length=30)
mobile = models.CharField(max_length=11)
View
from django.shortcuts import render
from django.template import loader
from .models import Account, Connectdef index(request):
userlist = Account.objects.all()
context = {"userlist": userlist}
return render(request,"one_to_one/index.html", context)def detail(request, id):
user = Account.objects.get(pk=id)
context = {"user": user}
return render(request,"one_to_one/detail.html", context)
Template
index.html
<h1>账号信息</h1>
<ul>
{% for user in userlist %}
<li>
<a href="one_to_one/{{ user.id }}/">{{ user.username }}--{{ user.register }}</a>
</li>
{% endfor %}
</ul>detail.html
<h1>{{ user.username }}</h1>
<ul>
<li>{{ user.connect.address }}</li>
<li>{{ user.connect.mobile }}</li>
</ul>
2、一对多:图书和英雄
Model
图书
class BookInfo(models.Model):
book_name = models.CharField(max_length=20)
publish_date = models.DateTimeField()英雄
class HeroInfo(models.Model):
name = models.CharField(max_length=20)
gender = models.BooleanField(default=True)
content = models.CharField(max_length=100)
book = models.ForeignKey("BookInfo", on_delete=models.CASCADE)
View
def index(request):
booklist = BookInfo.objects.all()
context = {"booklist":booklist}
return render(request,"booktest/index.html", context)def detail(request, id):
book = BookInfo.objects.get(pk=id)
context = {"book": book}
return render(request,"booktest/detail.html", context)
Template
index.html
<h1>图书列表</h1>
<ul>
{% for book in booklist %}
<li>
<a href="{% url 'booktest:detail' book.id %}">{{ book.book_name }}</a>
</li>
{% endfor %}
</ul>detail.html
<h1>{{ book.book_name }}</h1>
<ul>
{% for hero in book.heroinfo_set.all %}
<li>
{{ hero.name }}--{{ hero.content }}
</li>
{% endfor %}
</ul>
3、多对多:电脑和软件
Model
电脑
class Computer(models.Model):
id = models.AutoField(primary_key=True)
host = models.CharField(max_length=20)软件
class Application(models.Model):
name = models.CharField(max_length=20)
relation = models.ManyToManyField(to='Computer')
View
def index(request):
computerlist = Computer.objects.all()
context = {"computerlist": computerlist}
return render(request,"many_to_many/index.html", context)def detail(request, id):
computer = Computer.objects.get(pk=id)
context = {"computer": computer}
return render(request,"many_to_many/detail.html", context)
Template
index.html
<h1>主机列表</h1>
<ul>
{% for computer in computerlist %}
<li>
<a href="{{ computer.id }}/">{{ computer.host }}</a>
</li>
{% endfor %}
</ul>detail.html
<h1>{{ computer.host }}</h1>
<ul>
安装软件
{% for application in computer.application_set.all %}
<li>
{{ application.name }}
</li>
{% endfor %}
</ul>
网友评论