【问题标题】:Django extending model post_saveDjango 扩展模型 post_save
【发布时间】:2020-11-29 12:15:56
【问题描述】:

尝试使用 post_save 扩展我的模型:

class Profile(models.Model):
    account = models.OneToOneField(Account, on_delete=models.CASCADE)

def create_account_profile(sender, **kwargs):
    if kwargs['created']:
        account_profile = Account.objects.create(account=kwargs['instance'])



post_save.connect(create_account_profile, sender=Account)

得到以下错误:

Account() got an unexpected keyword argument 'account'

解决方案:

def create_account_profile(sender, instance, **kwargs):
    if kwargs['created']:
        account_profile = Profile.objects.create(account=instance)


post_save.connect(create_account_profile, sender=Account)

【问题讨论】:

    标签: python-3.x django django-signals


    【解决方案1】:

    您正在尝试创建一个新的 Account 对象,您需要从 Account 模型而不是 Profile 发送 related_name。

    def create_account_profile(sender, instance, **kwargs):
        if kwargs['created']:
            account_profile = Account.objects.create(profile=instance)
    
    

    据我了解,您想在创建个人资料时创建关联的 Account 对象?

    如果是这样,您的 post_save 没有使用正确的发件人?

    post_save.connect(create_account_profile, sender=Profile)
    

    【讨论】:

    • @Arik 你能更新我的答案是否正确吗?
    • 您的答案不正确。获取:无法分配“”:Account.profile”必须是“Profile”实例。
    • 现在它可以让我无错误地保存帐户,但配置文件不会自动保存在其模型中。
    • 我已经弄明白了,谢谢你的帮助。欢迎查看编辑后的原代码。
    猜你喜欢
    • 2016-10-12
    • 2011-02-28
    • 2013-04-10
    • 2013-12-06
    • 2018-01-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多