python - 添加保存的 FK 时 NoneType 对象不可调用

标签 python django django-models

尝试保存广告事件时收到错误消息'NoneType'对象不可调用。在 Django 中,这是否意味着一旦我保存了对象 SingleVoucherReward(),我就无权访问它并且无法将其分配给我的 Campaign 对象?

single_voucher_reward = SingleVoucherReward()
single_voucher_reward.description = "test"
single_voucher_reward.save()

Campaign.participant_reward(single_voucher_reward)
Campaign.save()

型号:

class Campaign(models.Model):
    name = models.CharField(max_length=60, help_text="Give your campaign a name i.e Xmas Offer")

    participant_reward_content_type = models.ForeignKey(ContentType,
                                                        editable=False,
                                                        related_name='%(app_label)s_%(class)s_as_participant',
                                                        )
    participant_reward_object_id = models.PositiveIntegerField()
    participant_reward = generic.GenericForeignKey('participant_reward_content_type', 'participant_reward_object_id')

最佳答案

您正在尝试将事物分配给类,而不是类的实例。尝试:

campaign = Campaign()
campaign.participant_reward = single_voucher_reward
campaign.save()

campaign = Campaign(participant_reward = single_voucher_reward)
campaign.save()

关于python - 添加保存的 FK 时 NoneType 对象不可调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19709394/

相关文章:

python - 使用scrapy点击网站上的按钮

python - 如何将列表列表中的所有数字变成整数

python - 使用 daphne : Requested setting INSTALLED_APPS, 部署 django Web 应用程序但未配置设置时出错

python - 如何正确设置 Django 模板路径?

python - Django 中的模型历史

django - ModelForm clean_xxxx() 适用于 CharField,不适用于 URLField。 Django 1.5

django - 与 Django 的唯一外键对

python - 将边缘检测转换为蒙版

python - Killer-web-development.com 的 selenium 和 web2py 不起作用

python - 如何询问for里面是否table1.id == table2.id?