django中如何实现model对象加入装饰器
admin
2023-08-02 16:40:08
0

#在现有的对象加入日期修改Mixin

class Person(CreationModificationDateMixin):

多出字段:

| created          | datetime(6)  | NO   |     | NULL    |                |

| modified         | datetime(6)  | YES  |     | NULL    |                |

#加入url MinIn

class Person(UrlMixin):

#加入原数据MInxIn

class Person(MetaTagsMixin):

多出字段:

| meta_keywords    | varchar(255) | NO   |     | NULL    |                |

| meta_description | varchar(255) | NO   |     | NULL    |                |

| meta_author      | varchar(255) | NO   |     | NULL    |                |

| meta_copyright   | varchar(255) | NO   |     | NULL    |                |

# -*- coding: UTF-8 -*-
from __future__ import unicode_literals
import urlparse

from django.conf import settings
from django.utils.timezone import now as timezone_now
from django.utils.safestring import mark_safe
from django.template.defaultfilters import escape
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes.fields import GenericForeignKey
from django.core.exceptions import FieldError


### See recipe "Model mixin with URL-related methods"

class UrlMixin(models.Model):
    """
    A replacement for get_absolute_url()
    Models extending this mixin should have either get_url or get_url_path implemented.
    http://code.djangoproject.com/wiki/ReplacingGetAbsoluteUrl
    """
    class Meta:
        abstract = True

    def get_url(self):
        if hasattr(self.get_url_path, "dont_recurse"):
            raise NotImplementedError
        try:
            path = self.get_url_path()
        except NotImplementedError:
            raise
        website_url = getattr(settings, "DEFAULT_WEBSITE_URL", "http://127.0.0.1:8000")
        return website_url + path
    get_url.dont_recurse = True

    def get_url_path(self):
        if hasattr(self.get_url, "dont_recurse"):
            raise NotImplementedError
        try:
            url = self.get_url()
        except NotImplementedError:
            raise
        bits = urlparse.urlparse(url)
        return urlparse.urlunparse(("", "") + bits[2:])
    get_url_path.dont_recurse = True

    def get_absolute_url(self):
        return self.get_url_path()


### See recipe "Model mixin handling creation and modification dates"

class CreationModificationDateMixin(models.Model):
    """
    Abstract base class with a creation and modification date and time
    """

    created = models.DateTimeField(
        _("creation date and time"),
        editable=False,
    )

    modified = models.DateTimeField(
        _("modification date and time"),
        null=True,
        editable=False,
    )

    def save(self, *args, **kwargs):
        if not self.pk:
            self.created = timezone_now()
        else:
            # To ensure that we have a creation data always, we add this one
            if not self.created:
                self.created = timezone_now()

            self.modified = timezone_now()

        super(CreationModificationDateMixin, self).save(*args, **kwargs)
    save.alters_data = True

    class Meta:
        abstract = True


### See recipe "Model mixin taking care of meta tags"

class MetaTagsMixin(models.Model):
    """
    Abstract base class for meta tags in the  section
    """
    meta_keywords = models.CharField(
        _("Keywords"),
        max_length=255,
        blank=True,
        help_text=_("Separate keywords by comma."),
    )
    meta_description = models.CharField(
        _("Description"),
        max_length=255,
        blank=True,
    )
    meta_author = models.CharField(
        _("Author"),
        max_length=255,
        blank=True,
    )
    meta_copyright = models.CharField(
        _("Copyright"),
        max_length=255,
        blank=True,
    )

    class Meta:
        abstract = True

    def get_meta_keywords(self):
        meta_tag = ""
        if self.meta_keywords:
            meta_tag = """\n""" % escape(self.meta_keywords)
        return mark_safe(meta_tag)

    def get_meta_description(self):
        meta_tag = ""
        if self.meta_description:
            meta_tag = """\n""" % escape(self.meta_description)
        return mark_safe(meta_tag)

    def get_meta_author(self):
        meta_tag = ""
        if self.meta_author:
            meta_tag = """\n""" % escape(self.meta_author)
        return mark_safe(meta_tag)

    def get_meta_copyright(self):
        meta_tag = ""
        if self.meta_copyright:
            meta_tag = """\n""" % escape(self.meta_copyright)
        return mark_safe(meta_tag)

    def get_meta_tags(self):
        return mark_safe("".join((
            self.get_meta_keywords(),
            self.get_meta_description(),
            self.get_meta_author(),
            self.get_meta_copyright(),
        )))


### See recipe "Model mixin handling generic relations"

def object_relation_mixin_factory(
        prefix=None,
        prefix_verbose=None,
        add_related_name=False,
        limit_content_type_choices_to={},
        limit_object_choices_to={},
        is_required=False,
    ):
    """
    returns a mixin class for generic foreign keys using
    "Content type - object Id" with dynamic field names.
    This function is just a class generator

    Parameters:
    prefix : a prefix, which is added in front of the fields
    prefix_verbose :    a verbose name of the prefix, used to
                        generate a title for the field column
                        of the content object in the Admin.
    add_related_name :  a boolean value indicating, that a
                        related name for the generated content
                        type foreign key should be added. This
                        value should be true, if you use more
                        than one ObjectRelationMixin in your model.

    The model fields are created like this:

    <>_content_type :   Field name for the "content type"
    <>_object_id :      Field name for the "object Id"
    <>_content_object : Field name for the "content object"

    """
    p = ""
    if prefix:
        p = "%s_" % prefix

    content_type_field = "%scontent_type" % p
    object_id_field = "%sobject_id" % p
    content_object_field = "%scontent_object" % p

    class TheClass(models.Model):
        class Meta:
            abstract = True

    if add_related_name:
        if not prefix:
            raise FieldError("if add_related_name is set to True, a prefix must be given")
        related_name = prefix
    else:
        related_name = None

    optional = not is_required

    ct_verbose_name = (
        _("%s's type (model)") % prefix_verbose
        if prefix_verbose
        else _("Related object's type (model)")
    )

    content_type = models.ForeignKey(
        ContentType,
        verbose_name=ct_verbose_name,
        related_name=related_name,
        blank=optional,
        null=optional,
        help_text=_("Please select the type (model) for the relation, you want to build."),
        limit_choices_to=limit_content_type_choices_to,
    )

    fk_verbose_name = (prefix_verbose or _("Related object"))

    object_id = models.CharField(
        fk_verbose_name,
        blank=optional,
        null=False,
        help_text=_("Please enter the ID of the related object."),
        max_length=255,
        default="",  # for south migrations
    )
    object_id.limit_choices_to = limit_object_choices_to
    # can be retrieved by MyModel._meta.get_field("object_id").limit_choices_to
    content_object = GenericForeignKey(
        ct_field=content_type_field,
        fk_field=object_id_field,
    )

    TheClass.add_to_class(content_type_field, content_type)
    TheClass.add_to_class(object_id_field, object_id)
    TheClass.add_to_class(content_object_field, content_object)

    return TheClass

相关内容

热门资讯

中国的长征火箭做到了!外媒的反... 北京时间7月10日中午12时许,中国的长征十号乙运载火箭,用中国自己首创的海上网系回收技术,成功实现...
惊魂5分钟,客机飞行中舷窗炸裂... 当地时间7月10日上午,瑞安航空一架波音737-800客机在起飞爬升时,一个舷窗玻璃突然破碎,一名靠...
委内瑞拉强震遇难人数升至411... △资料图当地时间10日,委内瑞拉全国代表大会主席豪尔赫·罗德里格斯通过社交媒体通报,该国日前发生的强...
科学与健康|国家自然科学奖一等... 7月8日,2025年度国家科学技术奖揭晓。自1999年《国家科学技术奖励条例》实施以来,国家自然科学...
能跟拍能自动剪辑,摄影机器人是... 构图图歪了、对焦慢了、关键时刻快门没按下去,“男朋友拍的照片没法看”——这大概是互联网上最经久不衰的...
古巴一周内再次全国大停电 新华社哈瓦那7月10日电(记者蒋彪 李子健)古巴电力联盟10日发表声明说,当地时间当天16时30分,...
财经聚焦丨从“技术可用”到“商...   新华社北京7月10日电 题:从“技术可用”到“商业可赚” AI智能体加速落地   新华社记者张骁...
原创 全... 受内存存储芯片涨价的影响,手机行业也因为成本飙升而导致新机价格大涨,因此进入全线收缩模式。对于华米O...
伊朗外交部:从未提出过与美国谈... 伊朗外交部发言人巴加埃10日表示,伊朗从未提出过与美国谈判的诉求,但同意调解方访问伊朗。伊朗外交部发...
泽连斯基宣布成立乌军远程打击司... △乌克兰总统泽连斯基(资料图)乌克兰总统泽连斯基10日表示,他已签署命令,在乌克兰武装部队内部设立一...