2、连表结构
- 一对多:models.ForeignKey(其他表)
- 多对多:models.ManyToManyField(其他表)
- 一对一:models.OneToOneField(其他表)
model.py
from django.db import models
class Blog(models.Model):
name = models.CharField(max_length=100)
tagline = models.TextField()
class Author(models.Model):
name = models.CharField(max_length=50)
email = models.EmailField()
class Entry(models.Model):
blog = models.ForeignKey(Blog)
headline = models.CharField(max_length=255)
body_text = models.TextField()
pub_date = models.DateField()
mod_date = models.DateField()
authors = models.ManyToManyField(Author)
n_comments = models.IntegerField()
n_pingbacks = models.IntegerField()
rating = models.IntegerField()
表结构:
from django.shortcuts import render总结:
from django.http import HttpResponse
from app01 import models
def index(req):
#正向查找
"""
ret = models.Author.objects.all()
print(type(ret),ret,ret.query)
#ret是QuerySet,一个特殊的对象
for item in ret:
#item 每一行数据 是一个对象
print(item,item.name)
ret1 = models.Author.objects.all().values("id")
print(type(ret1), ret1, ret1.query)
# ret是QuerySet,一个特殊的对象
for item in ret1:
# item 每一行数据 是一个字典 {'id': 1}
print(item,item['id'])
ret1 = models.Author.objects.all().values_list("id","name")
print(type(ret1), ret1, ret1.query)
# ret是QuerySet,一个特殊的对象
for item in ret1:
# item 每一行数据 是一个元祖(1, '李四')
print(item)
"""
# ret = models.Entry.objects.all()
# for item in ret:
# #item 每一行数据 是一个对象
# #item.blog 是外键 是一个对象 包含关联表所有信息
# #item.blog_id 关联的外键字段
# #item.blog.name item.外键字段.name
# print(item,item.headline,item.blog,item.blog_id,item.blog.name)
#双下划线的魅力
#注:fitter() 里面也要用__双下划线
# ret = models.Entry.objects.all().values("headline","blog__name")
# for item in ret:
# # item 每一行数据 是一个字典
# # blog__name 外键字段__name 双下划线获取关联表字段 {'headline': 'hello1', 'blog__name': 'blog1'}
# print(type(item),item)
#反向查找
ret = models.Blog.objects.filter(name="blog1").first()
print(ret,ret.name,ret.id)
#表名_set.all()
blog_info = ret.entry_set.all()
print(blog_info)
for item in blog_info:
print(item.headline,item.body_text,item.blog_id)
return HttpResponse("hello")
本文来自博客园,作者:孙龙-程序员,转载请注明原文链接:https://www.cnblogs.com/sunlong88/articles/8691591.html