Skip to main content
 首页 » 编程设计

python之django 根据模型属性自动填充一些数据

2024年09月03日30kevingrace

我正在研究一个概念,我想在保存模型时捕获某些信息。为了了解全貌,我有一个具有以下模型的应用程序核心

核心/模型.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') 

审计模型是一种通用的内容类型,目前正在将其附加到其他应用程序中,例如博客

博客/模型.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 核心本身内部的保存方法。这段代码将始终检查是否存在具有以下名称的属性,因此会在 aduti 表中创建一条记录。

请您参考如下方法:

我只是在我的模型类或管理器中创建一个函数,然后从我的表单保存中调用它(无论你在哪里)

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)