如果我创建MyFile对象,将自动创建Document对象

时间:2013-05-27 12:15:53

标签: django

如何创建这样的东西:

如果我创建了MyFile个对象,则会自动创建Document个对象。(rootfile应为ForeignKeyMyFile

class MyFile(models.Model):
    user = models.ForeignKey(User)
    path = models.FileField(upload_to="files")

class Document(models.Model):
    rootfile = models.ForeignKey(MyFile)
    user = models.ForeignKey(User,related_name='doc_owner')
    title = models.CharField(max_length=255)
    description = models.TextField()
    content = models.TextField()

1 个答案:

答案 0 :(得分:0)

MyFile上使用post_save()信号,如果是新的,请创建Document对象。

@receiver(post_save, sender=MyFile)
def my_handler(sender, **kwargs):
    if kwargs['created']:
        #create document object appropriately.
        document = Document()
        document.rootfile = kwargs['instance']
        document.save()