python-3.x - 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)
解决方案
您正在尝试创建一个新的 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)
推荐阅读
- r - 在 MLR 中,如何仅将逻辑超参数设置为 TRUE 或 FALSE?
- azure - Azure 前门 SSL 证书更新
- go - skipDefaultCheckout true 选项是跳过所有阶段并进入 postActions 阶段
- android - 如何创建通用改造服务
- python - 如何使用 django 创建下载链接?
- c++ - 如何在矢量容器中打印带有空格的代码
- php - 在 heroku 上提交表单时出现 Laravel 319 页面过期错误
- mongoose - GraphQLError:ID 不能代表值:
" - node.js - Azure,保持网站正常运行以执行常规批处理作业
- spring-boot - 在 springboottest 中从默认 applicaton.yml 设置 testcontainer 属性的更好方法