首页 > 解决方案 > 如何在 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 对象是在编辑客户端对象之后创建的,而不是在创建之后。

标签: pythondjangodjango-models

解决方案


我使用 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()

推荐阅读