首页 > 其他分享 >django-content-type简单示例

django-content-type简单示例

时间:2023-04-07 15:46:53浏览次数:36  
标签:示例 models 模型 object content type id

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

 

标签:示例,models,模型,object,content,type,id
From: https://www.cnblogs.com/52-qq/p/17296383.html

相关文章

  • 免费分享前端面试题,vue面试题,TypeScript基础知识点 PDF格式
    免费分享前端资料,面试题,电子书接前端开发,带徒弟,一对一教学,远程协助,bug修改微信:......
  • Python调用TensorFlow时出现:FutureWarning: Passing (type, 1) or '1type' as a synon
    百度了很多说是numpy版本过高,将numpy版本降低即可,我降低为1.16.2但是会碰到pipuninstallnumpy卸载不掉的问题我一直忽视了是在conda创建的虚拟环境acc中运行的这个代码,进入cmdpipuninstall时没注意是在base环境下,还是在自己创建的虚拟环境下,一直uninstall不掉numpy,原因我......
  • FastReport 复选框示例
    usingSystem;usingSystem.Collections;usingSystem.Collections.Generic;usingSystem.ComponentModel;usingSystem.Windows.Forms;usingSystem.Drawing;usingSystem.Data;usingFastReport;usingFastReport.Data;usingFastReport.Dialog;usingFastReport.......
  • Vue中axios请求后res返回204,no content,res.data为undefind
    一直以为后台只要返回200-299之间的状态码就没问题,就是这个错误认知,花了三个小时终于想到解决办法附上axios 地址  axios中文文档|axios中文网|axios(axios-js.com)前面一直想着后台能接收处理请求,肯定不是后台问题,一直花时间配置前端请求指令,以及设置响应拦截器查看情况......
  • VSCode自建vue示例模板
    步骤打开File->Preferences->ConfigureUserSnippets选择NewGlobalSnippetsfile...输入名字(自定义),填入以下内容,注意修改vue.js路径{"Printtoconsole":{"prefix":"vue","body":["<scrip......
  • 常用Content-Type汇总
    MIMEtype定义媒体类型(通常称为MultipurposeInternetMailExtensions或MIME类型)是一种标准,用来表示文档、文件或字节流的性质和格式。语法MIME的组成结构非常简单;由类型与子类型两个字符串中间用'/'分隔而组成。不允许空格存在。type表示可以被分多个子类的独......
  • docker启动报错the backing xfs filesystem is formatted without d_type support
    WARNING:overlay2:thebackingxfsfilesystemisformattedwithoutd_typesupport,whichleadstoincorrectbehavior.Reformatthefilesystemwithftype=1toenabled_typesupport.Runningwithoutd_typesupportwillnotbesupportedinfu......
  • 思考 TypeScript namespace,复习 class 语法
    前言据我所知,早期JavaScript没有class语法,很多都是函数,即便是现在的class本质上也是一个函数。在这里不说函数与class之间的关系和区别。下面将从class语法上讲解,阐述为什么有class以及作用;对class语法进行了探讨之后,再思考TypeScript的namespace给我们带来......
  • php上传文件简单示例
    php上传文件简单示例 <?php$log='';$buf=ob_get_contents();ob_end_clean();$postmaxsize=trim(ini_get('post_max_size'));//preg_match_all('/\d+/',$postmaxsize,$arr);//$number=$arr[0][0];//if(strpos($postmaxsize,&#......
  • OpenCV [c++](图像处理基础示例小程序汇总)
    一、图像读取与显示#include<opencv2/opencv.hpp>#include<iostream>usingnamespacecv;usingnamespacestd;intmain(){ stringpath="Resources/lambo.png";//图片的路径名 Matimg=imread(path);//将图片加载后赋值到图像变量img中//if(path.empty()){......