django-content-type简单示例
from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.contenttypes.models import ContentType from django.db import models class Comment(models.Model): content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') text = models.TextField() def __str__(self): return self.text
from django.contrib.contenttypes.models import ContentType from myapp.models import Blog, Comment blog = Blog.objects.get(id=1) comment = Comment(text='This is a comment.') comment.content_object = blog comment.content_type = ContentType.objects.get_for_model(blog) comment.object_id = blog.id comment.save()
使用 ContentType 和自己的模型结合起来使用时,通常需要创建一个通用的模型,这个模型可以跟任何其他模型结合起来使用。这个通用的模型需要包含以下两个字段: content_type:用于存储与这个对象相关联的模型类型。 object_id:用于存储与这个对象相关联的模型对象的 ID。 下面是一个使用 ContentType 和自己的模型结合起来使用的例子: python Copy code from django.db import models from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes.fields import GenericForeignKey class Comment(models.Model): content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') text = models.TextField() created_at = models.DateTimeField(auto_now_add=True) 在上面的代码中,我们创建了一个名为 Comment 的模型,这个模型包含了一个 content_type 字段、一个 object_id 字段和一个 content_object 字段。content_type 字段是一个外键,指向 ContentType 模型,用于存储与这个对象相关联的模型类型。object_id 字段是一个整数字段,用于存储与这个对象相关联的模型对象的 ID。content_object 字段是一个通用的外键,使用 GenericForeignKey 字段类型,用于关联到任何模型。 使用上述模型,我们可以将 Comment 模型与任何其他模型关联起来。例如,如果我们想将 Comment 模型与 Article 模型关联起来,我们可以像这样创建一条评论: python Copy code from django.contrib.contenttypes.models import ContentType article = Article.objects.get(id=1) content_type = ContentType.objects.get_for_model(article) comment = Comment( content_type=content_type, object_id=article.id, text='This is a comment on the article.', ) comment.save() 在上面的代码中,我们首先获取了一个 Article 对象,然后获取了与该对象相关联的模型类型。接着,我们创建了一个 Comment 对象,并将模型类型、
本文来自博客园,作者:一石数字欠我15w!!!,转载请注明原文链接:https://www.cnblogs.com/52-qq/p/17296383.html
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek “源神”启动!「GitHub 热点速览」
· 我与微信审核的“相爱相杀”看个人小程序副业
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· 如何使用 Uni-app 实现视频聊天(源码,支持安卓、iOS)
· C# 集成 DeepSeek 模型实现 AI 私有化(本地部署与 API 调用教程)
2018-04-07 Django项目开发-小技巧
2018-04-07 前端验证后端验证码问题