美文网首页
Django中ContentType学习

Django中ContentType学习

作者: brafei | 来源:发表于2019-06-10 22:50 被阅读0次

模型

models.py

from django.db import models
from django.db.models.fields import exceptions
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.utils import timezone


# Create your models here.
class ReadNum(models.Model):
    read_num = models.IntegerField(default=0)
    content_type = models.ForeignKey(ContentType, on_delete=models.DO_NOTHING)
    object_id = models.PositiveIntegerField()
    content_object = GenericForeignKey('content_type', 'object_id')


class ReadNumExpandMethod:
    def get_read_num(self):
        try:
            ct = ContentType.objects.get_for_model(self)
            readnum = ReadNum.objects.get(content_type=ct, object_id=self.pk)
            return readnum.read_num
        except exceptions.ObjectDoesNotExist:
            return 0


class ReadDetail(models.Model):
    date = models.DateTimeField(default=timezone.now)
    read_num = models.IntegerField(default=0)
    content_type = models.ForeignKey(ContentType, on_delete=models.DO_NOTHING)
    object_id = models.PositiveIntegerField()
    content_object = GenericForeignKey('content_type', 'object_id')

进入交互式命令行

python manage.py shell

查看ContentType调用结果

(InteractiveConsole)
>>> from mysite.models import *
>>> from read_statistics.models import *
>>> from django.shortcuts import get_object_or_404
>>> product_details = get_object_or_404(Product,id=5)  #从Product模型中找到ID值为5的对象
>>> product_details  #查看该对象是什么
<Product: <Media:黑钻涂层模板>>
>>> from django.contrib.contenttypes.models import ContentType #导入ContentType模型
>>> ct = ContentType.objects.get_for_model(product_details) #从ContentType中找寻到这个模型
>>> product_details.id #查看这个模型对应的ID值与上文的初值相同
5
>>> from read_statistics.models import ReadNum, ReadDetail
>>> ReadNum.objects.get_or_create(content_type = ct, object_id=product_details.pk)
(<ReadNum: ReadNum object (2)>, False) #查看调用ReadNum模型时返回的时什么参数

>>> readnum, created = ReadNum.objects.get_or_create(content_type = ct, object_id=
product_details.pk) #采用相同的参数模式,见名知意
>>> readnum
<ReadNum: ReadNum object (2)>
>>> created
False
>>> readnum.read_num #调用readnum中read_num
1
>>> readnum.id #调用readnum中id
2





相关文章

网友评论

      本文标题:Django中ContentType学习

      本文链接:https://www.haomeiwen.com/subject/oylxfctx.html