Django模型,默认记录

时间:2014-11-27 00:10:24

标签: python django django-models

我是Django的初学者,我现在正在学习模特。 我在后端有两张桌子,一张是另一张桌子(1对多的关系)。 到目前为止,非常好。

我想要做的是设置Django,这样如果在父表中创建了一条记录,子表将自动创建3条记录。

我该如何编程呢? 感谢。

1 个答案:

答案 0 :(得分:0)

您可能对以下内容感兴趣:

# ... other imports ...
from django.db.models.signals import post_save, pre_save

class Parent(models.Model)

  # this decorator & this method go inside your model
  @staticmethod
  def create_children(sender, instance=None, **kwargs):
      for x in range(3):

        # I'm assuming you want the child to be linked to the parent immediately.  
        # You can set any other attributes you want here too, of course.
        child = Child(parent = instance)
        child.save()

pre_save.connect(Parent.create_children, Parent)

请注意,在pre_save.connect()调用中,您可以调用任何[SomeClass]。[SomeMethodOfThatClass](这是第一个参数)来保存其他一些类(这是第二个参数)。但在实践中,我并不认为自己曾经这样做过,而且我不确定你是否需要这样做。