I have tried this a few ways but am stuck and unsure where to go. My model (ExampleModStack) has a toadd_fk which is a foreign key obtained from a API. I want to use this to create a forign key refernce to the Toadd model when the ExampleModStack is created. I create ExampleModStack model by reading the API values so I need a funciton to do this for me. I was thinking of using signals pre_save function so that I can set the toadd relationship there. Here is my code:
class ExampleModStack(models.Model):
toadd_fk = models.IntegerField()
toadd = models.ForeignKey(
Toadd,
null=True,
on_delete=models.CASCADE,
related_name='%(class)s_toadd'
)
class Meta:
verbose_name = 'example_mod_stack'
verbose_name_plural = 'example_mods_stack'
def __str__(self):
return str(self.id)
@receiver(pre_save)
def referenc_product(cls, instance, **kwargs):
cls.toadd = Product.objects.get(id=cls.toadd_fk)
I can not get this to work though. Does anyone know a way to make this functional?
Specify a sender as without doing this, the receiver would execute each time a model is saved:
@receiver(pre_save, sender=ExampleModStack)
def add_toadd(sender, **kwargs):
place your logic here
By specifying sender=ExampleModStack the receiver would execute only when an ExampleModStack is saved. Create additional function in your ExampleModStack which would add the "toadd" field and invoke that function in your receiver.
Also note that in your code you are trying to add a Product object to your toadd field which accepts Toadd objects.