使用self.id填充Django中的其他字段 [英] Using self.id to populate other fields in Django

查看:93
本文介绍了使用self.id填充Django中的其他字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to populate a field called 'identification' using the primary key 'id'. However, as you know, there is no way to know what 'id' an objects is going to be before it has been saved. Therefore, stubbornly I did this:

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

有趣的是,它可以在控制台中工作:

Amusingly, this works in console:

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

,但是当我转到模板检索该对象时:

but when I go to my template to retrieve this object:

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

现实罢工:

Identification: 

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

What is happening? Why is it working in console but not in a template?. What approach do you suggest to use an auto-populated field in other fields?.

非常感谢!

推荐答案

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

The problem is that you're not saving the changes to your database.

它可以在终端中运行,因为该特定模型实例(python对象-非常临时)具有 identification 充满。在视图或模板中访问它时,尚未调用 save()方法,因此属性/字段为空白。

It works in the terminal because that particular model instance (the python object - very much temporary) has the property identification filled. When you access it in a view or template, the save() method has not been called so the property / field is blank.

要使其生效,请在首次保存后再次调用save。另外,仅在模型创建时设置ID可能很有意义。在大多数情况下,每次初始保存都可以多打一个电话。

To make it work, call save again after your first save. Also, it might make sense to set the id only on model creation. One extra call per initial save isn't so big of a deal in most cases.

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)

这篇关于使用self.id填充Django中的其他字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆