Django根据模型属性自动填充数据

2 投票
1 回答
5043 浏览
提问于 2025-04-16 10:11

我正在做一个项目,想在保存模型的时候捕捉一些特定的信息。为了更好地理解这个过程,我有一个应用的核心部分,里面有以下模型。

core/models.py

from django.db import models
from django.contrib.auth.models import User
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic
from transmeta import TransMeta
from django.utils.translation import ugettext_lazy as _

import signals


class Audit(models.Model):
    ## TODO: Document
    # Polymorphic model using generic relation through DJANGO content type
    operation  = models.CharField(_('Operation'), max_length=40)
    operation_at = models.DateTimeField(_('Operation At'), auto_now_add=True)
    operation_by = models.ForeignKey(User, null=True, blank=True, related_name="%(app_label)s_%(class)s_y+")
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    content_object = generic.GenericForeignKey('content_type', 'object_id')

审计模型是一种通用的内容类型,我现在把它和其他应用连接起来,比如博客。

blog/models.py

from django.db import models
from django.contrib.contenttypes import generic
from django.contrib.contenttypes.models import ContentType
from django.template.defaultfilters import slugify
from django.utils.translation import ugettext_lazy as _
# Create your models here.



    class Meta:
        verbose_name_plural = "Categories"

class article(models.Model):
    title            = models.CharField(max_length=100)
    slug             = models.SlugField(editable=False, unique_for_year=True)
    content          = models.TextField()
    is_active        = models.BooleanField()
    published_at     = models.DateTimeField('Publish at',auto_now=True)
    related_articles = models.ManyToManyField('self', null=True, blank=True)
    audit_obj        = generic.GenericRelation('core.Audit', editable=False, null=True, blank=True)

我第一次尝试是创建了一个post_save信号,检查传入的实例是否包含audit_obj属性,然后用article.audit_obj.create().save()来保存记录。

可惜,这个方法没有完全奏效,因为我无法传递请求,也无法访问请求来获取用户信息。

所以,我在考虑创建一个自定义信号,并重写form_save方法(如果有的话),然后通过参数传递请求对象和模型对象。

有没有什么建议可以帮助我实现这个目标呢?

谢谢,

编辑(2011年1月20日):

感谢@Yuji的帮助。其实,我想实现的是尽量让我的代码保持简洁。最终我想要的是,每次创建新模型时,只需添加一个名为audit_obj的属性,然后创建一段代码,无论是信号还是重写django核心中的保存方法。这段代码会检查是否存在这个属性,并在审计表中创建一条记录。

1 个回答

3

我会在我的模型类或者管理类里创建一个函数,然后在保存表单的时候调用它(不管你的表单保存在哪里)。

class AuditManager(models.Manager):
    def save_from_object(self, request, obj):
        audit = Audit()
        audit.object_id = obj.id
        audit.operation_by = request.user
        # ...

        audit.save()


class Audit(models.Model):
    ## TODO: Document
    # Polymorphic model using generic relation through DJANGO content type
    operation  = models.CharField(_('Operation'), max_length=40)
    operation_at = models.DateTimeField(_('Operation At'), auto_now_add=True)
    operation_by = models.ForeignKey(User, null=True, blank=True, related_name="%(app_label)s_%(class)s_y+")
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    content_object = generic.GenericForeignKey('content_type', 'object_id')

    objects = AuditManager()


class MyBlogForm(forms.ModelForm):
    class Meta:
        model = article # btw I'd use Capital Letters For Classes

    def save(self, *args, **kwargs):
        super(MyBlogForm, self).save(*args, **kwargs)
        Audit.objects.save_from_object(request, self.instance)

撰写回答