首页 > 解决方案 > 创建新模型对象时,填充其中一个值

问题描述

我已经尝试了几种方法,但被卡住了,不知道该去哪里。我的模型(ExampleModStack)有一个 toadd_fk,它是从 API 获得的外键。我想在创建 ExampleModStack 时使用它来创建对 Toadd 模型的外键引用。我通过读取 API 值来创建 ExampleModStack 模型,因此我需要一个函数来为我执行此操作。我正在考虑使用信号 pre_save 函数,以便我可以在那里设置 toadd 关系。这是我的代码:

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)

我不能让它工作。有谁知道使这个功能起作用的方法?

标签: djangodjango-modelsdjango-signals

解决方案


指定发送方,因为不这样做,接收方将在每次保存模型时执行:

@receiver(pre_save, sender=ExampleModStack)
def add_toadd(sender, **kwargs):
    place your logic here

通过指定 sender=ExampleModStack 接收器将仅在保存 ExampleModStack 时执行。在您的 ExampleModStack 中创建附加函数,该函数将添加“toadd”字段并在您的接收器中调用该函数。

另请注意,在您的代码中,您尝试将 Product 对象添加到接受 Toadd 对象的 toadd 字段。


推荐阅读