集合创建者通过mixin动态修改

Set created by modified by dynamically with mixin

来自 rails 世界,我很高兴了解 mixins。我设置了一个

基本混合

core/mixins.py

from django.db import models
from django.contrib.auth.models import User

class Timestamps(models.Model):
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        abstract = True

然后我的 Event 模型在 core/my_app/models.py

from core import mixins as core_mixins

class Event(core_mixins.Timestamps):
    # ...

一切都很好,但是如果我想稍微扩展一下并创建一个更动态的混音怎么办?

高级混合

core/mixins.py

from django.db import models
from django.contrib.auth.models import User

from django.dispatch import receiver
from django.db.models.signals import pre_save
from cw_core.requestprovider.signals import get_request

class Trackable(models.Model):
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    created_by = models.ForeignKey(User, related_name='created_XXX') # <-- ???
    updated_by = models.ForeignKey(User, related_name='updated_XXX') # <-- ???

    class Meta:
        abstract = True

@receiver(pre_save, sender=Event) # <-- ???
def security_attributes(sender, instance, **kwargs):
    request = get_request()

    instance.updated_by = request.user

    if instance.id is None:
        instance.created_by = request.user

core/my_app/models.py

from core import mixins as core_mixins

class Event(core_mixins.Trackable):
    # ...

我的尝试是设置:

@receiver(pre_save, sender=self.__class__)

但我不确定这是否有效?建议的方法是什么?

只需使用现有功能https://docs.djangoproject.com/en/1.11/topics/db/models/#abstract-related-name

class Trackable(models.Model):
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    created_by = models.ForeignKey(User, related_name='created_%(class)s')
    updated_by = models.ForeignKey(User, related_name='updated_%(class)s')
    class Meta:
        abstract = True

第二部分还有解决方案

@receiver(pre_save)
def security_attributes(sender, instance, **kwargs):
    if not issubclass(sender, core_mixins.Trackable):
        return
    request = get_request()

    instance.updated_by = request.user

    if instance.id is None:
        instance.created_by = request.user

基本上你可以在信号处理器中过滤发件人。

还有还有django-model-utilshttps://django-model-utils.readthedocs.io/en/latest/models.html#timestampedmodel