gpt4 book ai didi

django - 使用 self.id 填充 Django 中的其他字段

转载 作者:行者123 更新时间:2023-12-04 03:07:07 25 4
gpt4 key购买 nike

我正在尝试使用主键“id”填充一个名为“identification”的字段。但是,如您所知,在保存对象之前无法知道对象的“id”是什么。因此,我固执地这样做了:

def save(self, *args, **kwargs):
super(Notifications, self).save(*args, **kwargs)
self.identification = str(self.id)

有趣的是,这在控制台中有效:

>>>new = Notifications.objects.create( # some fields to be filled )
>>>new.identification
'3' (# or whatever number)

但是当我转到我的模板来检索这个对象时:

{% for each in notifications %}
Identification: {{ each.identification }}
{% endfor %}

现实打击:

Identification: 

发生了什么事?为什么它在控制台中工作而不是在模板中工作?您建议使用哪种方法在其他字段中使用自动填充字段?

非常感谢!

最佳答案

问题是您没有将更改保存到数据库中。

它在终端中工作,因为那个特定的模型实例(python 对象 - 非常临时)填充了属性 identification。当您在 View 或模板中访问它时,save() 方法尚未被调用,因此属性/字段为空。

要使其正常工作,请在第一次保存后再次调用保存。此外,仅在创建模型时设置 id 可能是有意义的。在大多数情况下,每次初始保存一次额外调用并不是什么大不了的事。

def save(self, *args, **kwargs):
add = not self.pk
super(MyModel, self).save(*args, **kwargs)
if add:
self.identification = str(self.id)
kwargs['force_insert'] = False # create() uses this, which causes error.
super(MyModel, self).save(*args, **kwargs)

关于django - 使用 self.id 填充 Django 中的其他字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8905387/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com