django-content-type简单示例

发布时间 2023-04-07 15:40:47作者: 前方、有光
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 对象,并将模型类型、