首页 > 解决方案 > 在创建 django 时添加注册

问题描述

所以我正在尝试为 django 上的应用程序做一个 RESTFULL 后端。所以不需要视图,现在我在管理员处添加这个。我创建了 2 个模型表 1 和类别。每次我添加 table1 行时,我必须为每个类别插入 4 个类别和预算,最初为 0。我尝试使用 table 1 类中的方法覆盖保存方法。并在插入时插入,但由于参照完整性而出现错误。我有一些问题。1.- 最好的方法是什么?我见过 on_insert 事件,但我也读过不建议使用它。2.- 覆盖保存方法,将 table1 的引用留空?然后用最后一个插入更新?3.- 其他选择?

class table1(models.Model):
    table1field = models.CharField(max_length=100,default='')
    def  add_cat(self,cat):
        category.objects.create(descripcion_categoria_insumo='category 1', category=cat, budget=0)
        category.save()
        category.objects.create(descripcion_categoria_insumo='category 2', category=cat,budget=0)
        CategoriaInsumo.save()

        pass
    def save(self, *args, **kwargs):
        created = self.pk is None
        super(table1,self).save(*args, **kwargs)  # Call the "real" save() method.
        self.add_cat(self.pk)


class category(models.Model):
    desc_category =models.CharField(max_length=100,default='')
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    budget= models.DecimalField(default=0,max_digits=12,decimal_places=2 ,blank=True)

    category = models.ForeignKey(table1, on_delete=models.CASCADE,blank=True)
    def __str__(self):
        return self.desc_category


标签: pythondjangomodeloverriding

解决方案


您可以使用post_save 来自 django 的信号。使用信号,您可以设置一个函数以在每次发生某些事件时执行(这里的事件是向 table1 添加新条目)。

因此,您可以创建一个函数,每次创建 table1 对象时都会调用它:

from .models import table1, category
from django.db.models.signals import post_save
from django.dispatch import receiver

@receiver(post_save, sender=table1)
def save_profile(sender, instance, **kwargs):
    # create the categories
    category.objects.create(descripcion_categoria_insumo='category 1',
        category=cat, budget=0)
    .
    .
    .

instance是新创建的 table1 条目。

通常这个文件位于 singals.py 并且 django 默认不会加载它,所以你必须编辑你的 apps.py :

class YouAppConfig(AppConfig):
    .
    .
    .
    def ready():
        import .signals

推荐阅读