Ad

If I Create MyFile Object, Document Object Will Be Create Automatically

- 1 answer

How to create something like this:

If I create MyFile object, Document object will be create automatically.(rootfile should be ForeignKey to MyFile)

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()
Ad

Answer

Use post_save() signal on MyFile and if its new, create Document object too.

@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()
Ad
source: stackoverflow.com
Ad