python - 如何在 Django 中创建一个模型的对象,同时创建另一个不同的模型?
问题描述
这听起来很混乱,但我会把我的代码放在这里以便更好地理解我的问题。每次创建模型客户端对象时,我都想创建模型产品的新对象。我试图覆盖保存方法,但没有奏效。
class Product(models.Model):
text = CharField( ... )
class Client(models.Model):
name = CharField( ... )
** method here to create a new Product object when a Client object is created ?**
编辑:覆盖 save 方法的主要问题是 Product 对象是在编辑客户端对象之后创建的,而不是在创建之后。
解决方案
我使用 post_save 信号进行更好的处理,我必须指定我需要我创建的 Client 对象的 pk 才能创建 Product 对象。
@receiver(post_save, sender=Client)
def function_to_do_new_object(sender, instance, **kwargs):
obj = Product(text="Hello", id_of_client=int(instance.pk))
obj.save()
推荐阅读
- powershell - 将计算机列表导出到 CSV 有困难
- python - Python中异常处理的装饰器
- javascript - 如何使用 selenium for java 从 chrome 获取本地存储数据?
- javascript - 我们是否应该在 ES6 类的原型中包含方法以提高性能?
- python - 通过 API 访问 Help Scout 线程内容
- javascript - 在同一调用 SQL 2016 中从 WEB API 返回两个 JSON 对象
- pdf - 如何使用 iText 创建一个表格,以便所有列的宽度相同而不管内容如何?
- c# - 如何在 Unity 中正确检查 Internet 连接?
- node.js - 具有内容并接受编码标头的更大有效负载
- javascript - Angular Serving Assets 作为 MIME ('text/html')