0

Based on that question: How to Create new object automatically after creating other object in django?

I need a model that create automatic new objects while a new object is created. So I tried this

class Book(models.Model):
    author = models.CharField(max_length=30)
    title = models.CharField(max_length=30)
    foo = models.IntegerField(default=0)

    def save(self, *args, **kwargs):
        is_new = True if not self.id else False
        super(Book, self).save(*args, **kwargs)
        if is_new:
            part_2 = Book.objects.create(author_id = self.author.id,
                                         title = self.title,
                                         foo = self.title + 1,)

So my idea was that if I create a new Book instance it automatically creates a Book instance with the same data except foo, which should be raised.

While trying to save a new entry I get a Recursion Error

maximum recursion depth exceeded while calling a Python object
Request Method:     POST
Request URL:     
http://localhost:8000/admin/bookcreator/book/add/
Django Version:     2.2
Exception Type:     RecursionError
Exception Value:    

maximum recursion depth exceeded while calling a Python object


 /Django/bookcreator/models.py in save

 title = self.title, foo =  self.foo + 1,)
  • on new "Book" your save method is infinite. You need to think through what it is you want to do. If you just want a depth of 1, you can probably pass a `depth=n` kwarg to the save argument and handle that. – monkut Jun 06 '19 at 04:26
  • I would recommend creating two instances one-by-one, without using the `save()` override – JPG Jun 06 '19 at 04:27
  • What's the best way to do that automatically without using save() override? – Lukas Schönsgibl Jun 06 '19 at 18:52

0 Answers0