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

时间:2017-05-05 08:36:27

标签: django django-models mixins

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

Basic mixin

芯/ 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):
    # ...

一切都很愉快,但如果我想延长一点并创造一个更有活力的混音呢?

高级mixin

芯/ 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

芯/ my_app应用/ models.py

from core import mixins as core_mixins

class Event(core_mixins.Trackable):
    # ...
  • 如何动态设置related_name?我found this question但是我没有找到我可以在字符串中使用的变量,是否有任何文档?

  • 另外,我如何在@receiver电话中动态设置发件人?

我的尝试是设置:

@receiver(pre_save, sender=self.__class__)

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

1 个答案:

答案 0 :(得分:3)

只需使用现有功能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

第二部分还有解决方案https://stackoverflow.com/a/17173716/3627387

@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-utils https://django-model-utils.readthedocs.io/en/latest/models.html#timestampedmodel