Python contenttypes组件
介绍



应用场景
我们在网上po一段散文诗也可以po一张旅途的风景图,文字可以被评论,图片也可以被评论。我们需要在数据库中建表存储这些数据,我们可能会设计出下面这样的表结构。
class Post(models.Model):
"""帖子表"""
author = models.ForeignKey(User)
title = models.CharField(max_length=72) class Picture(models.Model):
"""图片表"""
author = models.ForeignKey(User)
image = models.ImageField() class Comment(models.Model):
"""评论表"""
author = models.ForeignKey(User)
content = models.TextField()
post = models.ForeignKey(Post, null=True, blank=True, on_delete=models.CASCADE)
picture = models.ForeignKey(Picture, null=True, blank=True, on_delete=models.CASCADE)
这表结构看起来不太简洁,我们画个图来看一下:

能用是能用,但是评论表有点冗余啊。好多列都空着呢啊!
我们优化一下,我们在评论表里不直接外键关联 文字和图片,而是存储一下关联的表名和字段,这样就好很多了。
看下图:

那我们不妨步子再大一点,再往前走一步试试,因为表名在评论里面重复了很多次,我们完全可以把Django项目中的表名都存储在一个表里面。然后评论表里外键关联这个表就可以了。

class Comment(models.Model):
"""评论表"""
author = models.ForeignKey(User)
content = models.TextField() content_type = models.ForeignKey(ContentType) # 外键关联django_content_type表
object_id = models.PositiveIntegerField() # 关联数据的主键
content_object = GenericForeignKey('content_type', 'object_id')
contenttypes使用
import os if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "about_contenttype.settings") import django
django.setup() from app01.models import Post, Picture, Comment
from django.contrib.auth.models import User
# 准备测试数据
user_1 = User.objects.create_user(username='aaa', password='123')
user_2 = User.objects.create_user(username='bbb', password='123')
user_3 = User.objects.create_user(username='ccc', password='123') post_1 = Post.objects.create(author=user_1, title='Python入门教程')
post_2 = Post.objects.create(author=user_2, title='Python进阶教程')
post_3 = Post.objects.create(author=user_1, title='Python入土教程') picture_1 = Picture.objects.create(author=user_1, image='小姐姐01.jpg')
picture_2 = Picture.objects.create(author=user_1, image='小姐姐02.jpg')
picture_3 = Picture.objects.create(author=user_3, image='小哥哥01.jpg') # 给帖子创建评论数据
comment_1 = Comment.objects.create(author=user_1, content='好文!', content_object=post_1)
# 给图片创建评论数据
comment_2 = Comment.objects.create(author=user_2, content='好美!', content_object=picture_1)
from django.contrib.contenttypes.fields import GenericRelation
class Post(models.Model):
"""帖子表"""
author = models.ForeignKey(User)
title = models.CharField(max_length=72) comments = GenericRelation('Comment') # 支持反向查找评论数据(不会在数据库中创建字段) class Picture(models.Model):
"""图片表"""
author = models.ForeignKey(User)
image = models.ImageField() comments = GenericRelation('Comment') # 支持反向查找评论数据(不会在数据库中创建字段)
查询示例:
post_1 = Post.objects.filter(id=1).first()
comment_list = post_1.comments.all()
Python contenttypes组件的更多相关文章
- Django contenttypes 组件
contenttypes组件 介绍 Django包含一个contenttypes应用程序(app),可以跟踪Django项目中安装的所有模型(Model),提供用于处理模型的高级通用接口. Conte ...
- Django contenttypes组件
contenttypes组件 介绍 Django包含一个contenttypes应用程序(app),可以跟踪Django项目中安装的所有模型(Model),提供用于处理模型的高级通用接口. Conte ...
- contenttypes组件 (处理大量外键)
介绍 Django contenttypes是一个非常有用的框架,主要用来创建模型间的通用关系(generic relation). https://www.cnblogs.com/huchong ...
- Django之contenttypes组件
目录 一. 介绍 二. 应用场景 1. 表结构设计的演变 2. GenericForeignKey和GenericRelation 3. 测试 一. 介绍 Django包含一个contenttypes ...
- Python标准组件ConfigParser配置文件解析器,保存配置时支持大写字母的方法
虽然自己已经改用xml作为配置文件首选格式了,但是有时候还是需要解析ini.cfg文件(为了兼容早期版本或者其他作者的软件). 基本上Python自带的ConfigParser足够应对了,但是美中不足 ...
- Python常用组件、命令大总结(持续更新)
Python开发常用组件.命令(干货) 持续更新中-关注公众号"轻松学编程"了解更多. 1.生成6位数字随机验证码 import random import string def ...
- Python分页组件
分页组件的实现: class Pagination(object): """ 自定义分页 """ def __init__(self,cur ...
- Python - Django - 组件
网站中通常会有一个导航条,如下图 这个导航条在很多页面都会存在 可以把导航条做成一个组件,让要显示导航条的网页包含 导航条组件 nav.html: <h1>假装这是一个导航条</h1 ...
- python 日志组件
日志组件: import logging import logging.handlers import os class logs(object): def __init__(self): self. ...
随机推荐
- cmd - 命令行窗口中文乱码
问题 在cmd窗口中输入curl www.baidu.com可以看到有中文乱码的现象,这是因为默认使用的是GBK编码.另外,curl是利用URL语法在命令行方式下工作的开源文件传输工具.它被广泛应用在 ...
- JS 两个数组合并
让我们先考虑下面这情况: 代码如下: var a = [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ];var b = [ "foo", "bar", ...
- IIS发布MVC应用程序问题
1.IIS7.5详细错误 HTTP 错误 500.19 - Internal Server Error 无法访问请求的页面,因为该页的相关配置数据无效 重复定义了“system.web.extensi ...
- Unity Shader入门精要学习笔记 - 第8章 透明效果
转载自 冯乐乐的 <Unity Shader入门精要> 透明是游戏中经常要使用的一种效果.在实时渲染中要实现透明效果,通常会在渲染模型时控制它的透明通道.当开启透明混合后,当一个物体被渲染 ...
- Java方式配置Spring MVC
概述 使用Java方式配置Spring MVC,以及回顾一下Spring MVC的各种用法. Spring MVC简述 关于Spring MVC的介绍网上有很多,这里就不再赘述了,只是要说一下,Spr ...
- poj2135 最小费用流
添加超级源点(与点1之间的边容量为2,权值为0)和超级汇点(与点N之间的边容量为2,权值为0),求流量为2的最小费用流.注意是双向边. #include <iostream> #inclu ...
- Ubuntu安装新英伟达驱动出现问题解决方法
ERROR: The Nouveau kernel driver is currently in use by your system. This driver is incompatible wit ...
- Windows Live Writer 2012发博客配置和技巧
一.软件准备: 最新版的是Windows Live Writer 2012,但是不提供单独的安装包,它是和微软其它软件一起的(包括MSN.Window Move Maker等),软件大小为131M,官 ...
- IOS之UI异步刷新
NSOperationQueue *operationQueue; // for rendering pages on second thread [operationQueue waitUn ...
- codevs 3129 奶牛代理商IX
时间限制: 1 s 空间限制: 32000 KB 题目等级 : 白银 Silver 题目描述 Description 小X从美国回来后,成为了USACO中国区的奶牛销售代理商,专门出售质优价廉的“ ...