Friday, May 29, 2020

Re: function model which generate a code for model field

Hello Derek,
Is it possible to retrieve the id of the previous recording from this function? If possible I could increment it to get the id of the current recording.
Anselme S.

Le ven. 29 mai 2020 à 06:08, Derek <gamesbook@gmail.com> a écrit :
The suggested code will not work because, at this point, the "id" has not yet been generated by the database (unlike the other data which is typically entered by the user).

You will need to move this code to a post_save signal function - https://docs.djangoproject.com/en/3.0/ref/signals/#post-save - where the "instance" object can be used to get the "id" value.

On Wednesday, 27 May 2020 14:22:41 UTC+2, Kasper Laudrup wrote:
Hi Anselme,


On 27/05/2020 13.33, Anselme SERI wrote:
>
> What I want to do is fill in the 'code' field of my 'Diploma' template.
> For example, the first record of the model will have the value
> 'BAC00001' in the 'code' field, the second 'BAC00002', ...., 'BAC01653'
> .....
> The approach I have chosen to achieve this objective consists in
> defining a function in the model which will retrieve the value of the
> last id of the last record, increment it then concatenate it to the
> chain to obtain the value of the code field of the new recording. code =
> chain + (lastid + 1) with chain = 'BAC000 ..'. I hope it's clear now?
>

There might be better ways to do this, but I would override the save()
method of your model with something like:

def save(self, *args, **kwargs):
     self.code = 'BAC{:05}'.format(self.id)
     super(MyModel, self).save(*args, **kwargs)

Untested, but hopefully you get the idea.

Kind regards,

Kasper Laudrup

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/bad64876-a692-463a-99af-5d491841d5a1%40googlegroups.com.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CACbA33oeQZxJ%2B59-6iX_8NDYb7tGCbMN4VSez8OTAnoFgrLfKA%40mail.gmail.com.

No comments:

Post a Comment