所以我正在尝试为 django 上的应用程序做一个 RESTFULL 后端。所以不需要任何 View ,现在我正在管理员处添加它。我创建了 2 个模型 表1、类别。每次我添加 table1 行时,我都必须为每个类别插入 4 个类别和预算,最初为 0。我尝试过在 table 1 类中使用一种方法来覆盖 save 方法。并在插入时插入,但由于引用完整性而出现错误。我有一些疑问。 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
最佳答案
您可以使用post_save
signal from 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)
.
.
.
实例
是新创建的table1条目。
通常这个文件位于singals.py,默认情况下django不会加载它,所以你必须编辑你的apps.py:
class YouAppConfig(AppConfig):
.
.
.
def ready():
import .signals
关于python - 在创建django时添加注册,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60424636/