django - 创建新模型对象时,填充其中一个值
问题描述
我已经尝试了几种方法,但被卡住了,不知道该去哪里。我的模型(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)
我不能让它工作。有谁知道使这个功能起作用的方法?
解决方案
指定发送方,因为不这样做,接收方将在每次保存模型时执行:
@receiver(pre_save, sender=ExampleModStack)
def add_toadd(sender, **kwargs):
place your logic here
通过指定 sender=ExampleModStack 接收器将仅在保存 ExampleModStack 时执行。在您的 ExampleModStack 中创建附加函数,该函数将添加“toadd”字段并在您的接收器中调用该函数。
另请注意,在您的代码中,您尝试将 Product 对象添加到接受 Toadd 对象的 toadd 字段。
推荐阅读
- core-data - 在 iOS13 中使用 NSPersistentCloudKitContainer 进行 CloudKit 同步
- cloud - 使用openstack上的配置文件登录时如何强制更改密码Windows服务器
- jpa - JPA getSingleResult() 没有收到任何实体错误
- java - 以一对一的关系分配值
- dialogflow-es - agent.set.context() 不工作 Dialogflow 实现
- c - 是否可以将 ICMP 协议与 Azure Sphere Dev Kit 一起使用?
- android - 使用 Primary Sorted Collection 的字段对二级集合进行排序
- rest - 如何处理 Rest Template 中的无效内容类型?
- python - 如何使 msvcrt.getch() 在 mintty 中的行为与在 cmd 中的行为相同?
- asp.net-core - 如何在 IIS Express 配置文件中定义 launchUrl