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

# Create your models here.


# 计数共用类
class CountNumExpandMethod:
    def get_read_num(self):
        """
        获取文章的阅读数
        :return: 返回该篇文章的阅读数
        """
        ct = ContentType.objects.get_for_model(self)
        readnum, created = ReadNum.objects.get_or_create(content_type=ct, object_id=self.pk)
        return readnum.read_num


# 阅读数计数
class ReadNum(models.Model):
    read_num = models.PositiveIntegerField(verbose_name="阅读数", default=0)
    content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
    object_id = models.PositiveIntegerField()
    content_object = GenericForeignKey('content_type', 'object_id')

    class Meta:
        verbose_name = "阅读数"
        verbose_name_plural = verbose_name


# 阅读数(天数)计数
class ReadDateDetail(models.Model):
    date = models.DateField(default=timezone.now)
    read_num = models.PositiveIntegerField(verbose_name="阅读数", default=0)
    content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
    object_id = models.PositiveIntegerField()
    content_object = GenericForeignKey('content_type', 'object_id')

    class Meta:
        verbose_name = "阅读数(天)"
        verbose_name_plural = verbose_name

