1👍
✅
The problem is that pre_init
signal doesn’t take instance parameter, so you are editing actual class (sender
). Try using post_init
signal which takes instance
parameter, so you can change it:
def init_my_parent(sender, instance, *args, **kwargs):
if not hasattr(instance,'child1'):
instance.child1 = MyChild1()
instance.child1.save()
if not hasattr(instance,'child2'):
instance.child2 = MyChild2()
instance.child2.save()
signals.post_init.connect(init_my_parent, sender=MyParent)
0👍
class MyChild1(models.Model):
attr1 = models.CharField(default='default value', max_length=100)
class MyChild2(models.Model):
pass
class MyParent(models.Model):
child1 = models.ForeignKey(MyChild1)
child2 = models.ForeignKey(MyChild2
using class instead of def, then it is going to be fine.
Source:stackexchange.com