首页 > 解决方案 > Django 扩展模型 post_save

问题描述

尝试使用 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.xdjangodjango-signals

解决方案


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

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

我的理解是,您想在创建 Profile 时创建关联的 Account 对象?

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

post_save.connect(create_account_profile, sender=Profile)

推荐阅读