Is it possible to create object when I created another object in Django?
I have code like this and I would like to create AnotherModel instance firstly and then Model instance (when creating AnotherModel).
class Model(models.Model):
name = models.CharFiled(max_length=50)
class AnotherModel(models.Model):
model = models.ForeignKey(Model, on_delete=models.CASCADE)
description = models.TextField()
I tried use Django signals - pre_save.
@receiver(pre_save, sender=AnotherModel)
def save_model(sender, **kwargs):
# some code
But I have exception like this:
ValueError: Cannot assign "u'Test": "AnotherModel.resource" must be a "Model" instance.
# some codethe wrong way, since you have set thenameof yourModelto themodel(wellresource) of yourAnotherModelinstead of its primary key. But that being said, Signals are usually not a good idea: lincolnloop.com/blog/django-anti-patterns-signals A lot of ORM calls like.update(..),.bulk_create, etc. can circumvent these.AnotherModel?