如果创建了新对象,Django可以自动创建其他对象吗?

时间:2019-06-06 04:22:35

标签: python django

基于该问题:How to Create new object automatically after creating other object in django?

我需要一个在创建新对象时会自动创建新对象的模型。所以我尝试了

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,)

所以我的想法是,如果我创建一个新的Book实例,它会自动创建一个Book实例,该实例除了foo之外应具有相同的数据。

尝试保存新条目时出现递归错误

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,)

0 个答案:

没有答案
相关问题