当我们通过models.py
或forms.py
创建另一个对象时,是否可以创建对象?
models.py
class Study(models.Model):
nameS= models.CharField(max_length=40)
def __init__(self):
System.create(Study=self)
class System(models.Model):
Name= models.TextField(max_length=25)
Study= models.OneToOneField(Study)
答案 0 :(得分:4)
试试这个,它应该在Test对象创建过程中只创建一次System对象:
class Test(models.Model):
nameS= models.CharField(max_length=40)
def save(self, *args, **kwargs):
if not self.pk: # the object doesn't have PK until the very first save
super(Test, self).save(*args, **kwargs)
Test2.objects.create(test=self)
else:
super(Test, self).save(*args, **kwargs)
您可能还需要填充field1
字段,因为根据您当前的设置它不能为NULL。
答案 1 :(得分:1)
您可以使用pre_save
信号:
# models.py
from django.db.models import pre_save
from django.dispatch import receiver
@receiver(pre_save, sender=Study)
def system_creator(**kwargs):
created = kwargs.get('created')
# flag `True` if object created now
if created:
study = kwargs.get('instance')
test = Test.objects.create(Study=study,...)