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 对象,并将模型类型、
复制代码

 

posted @   一石数字欠我15w!!!  阅读(43)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek “源神”启动!「GitHub 热点速览」
· 我与微信审核的“相爱相杀”看个人小程序副业
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· 如何使用 Uni-app 实现视频聊天(源码,支持安卓、iOS)
· C# 集成 DeepSeek 模型实现 AI 私有化(本地部署与 API 调用教程)
历史上的今天:
2018-04-07 Django项目开发-小技巧
2018-04-07 前端验证后端验证码问题
点击右上角即可分享
微信分享提示