问题
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 %}
reality strikes:
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?.
Thanks a lot!
回答1:
The problem is that you're not saving the changes to your database.
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.
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)
来源:https://stackoverflow.com/questions/8905387/using-self-id-to-populate-other-fields-in-django