Django创建对象

时间:2014-02-07 08:45:00

标签: django django-models django-forms

当我们通过models.pyforms.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)

2 个答案:

答案 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,...)