function model which generate a code for model field

56 views
Skip to first unread message

Anselme SERI

unread,
May 24, 2020, 11:48:29 AM5/24/20
to Django users
from django.db import models


def codeid():
lastid = MyModel.objects.last(id)
autocode = ''
if lastid == 0:
autocode = 'BAC000000001'
elif lastid != 0:
if len(lastid) <= 8:
lastid += 1
autocode = 'D/BAC/00000000' + lastid
elif 9 < len(lastid) <= 98:
lastid += 1
autocode = 'D/BAC/0000000' + lastid
elif 99 < len(lastid) <= 998:
lastid += 1
autocode = 'D/BAC/000000' + lastid
return autocode


class MyModel(models.Model):
libelle = models.CharField('Libellé', max_length=100)
code = models.CharField(max_length=30, unique=True, auto_created=codeid())

def __str__(self):
return self.code

Hello,

I try  to to write a correct function for my model which  generate a str + incremental number according last id model.

Pleaz help me.
 

Kasper Laudrup

unread,
May 24, 2020, 4:12:40 PM5/24/20
to django...@googlegroups.com
Hi Anselme,

On 24/05/2020 17.48, Anselme SERI wrote:
>
> I try  to to write a correct function for my model which  generate a str
> + incremental number according last id model.
>

Your code is obviously wrong for quite a few reasons, but I at least
simply cannot understand what you are trying to achieve.

What should the "correct function" do?

The id field of a model is already incremental. Do you simply want to
append that to a string and what do you want to do with that string?

Kind regards,

Kasper Laudrup

Anselme SERI

unread,
May 25, 2020, 4:33:30 PM5/25/20
to django...@googlegroups.com
hello,
I am trying to create a function which will recover the last id of my model which I will increment and add to a character string, and I would like to add this new value (x = last id incremented + string) be added to the "code" field "of my model when I make a new recording.
How else could we use the id field which automatically increments to perform such an action?

Anselme S.

--
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...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/65ffe493-1190-619a-f904-fbe35b60e3e3%40stacktrace.dk.

Derek

unread,
May 27, 2020, 2:52:10 AM5/27/20
to Django users
Its not clear what you mean by "last"; do you mean a record that already exists in the database and has a ID value - or do you want the ID of the current record?  Either way, the code field should not be resetting the '0' to a '1' as this is then misrepresenting the actual data.

PS The logic to create the string looks a bit clunky; why not use rjust to get the correct number of prefix zeros?


On Monday, 25 May 2020 22:33:30 UTC+2, Anselme SERI wrote:
hello,
I am trying to create a function which will recover the last id of my model which I will increment and add to a character string, and I would like to add this new value (x = last id incremented + string) be added to the "code" field "of my model when I make a new recording.
How else could we use the id field which automatically increments to perform such an action?

Anselme S.

Le dim. 24 mai 2020 à 20:12, Kasper Laudrup <lau...@stacktrace.dk> a écrit :
Hi Anselme,

On 24/05/2020 17.48, Anselme SERI wrote:
>
> I try  to to write a correct function for my model which  generate a str
> + incremental number according last id model.
>

Your code is obviously wrong for quite a few reasons, but I at least
simply cannot understand what you are trying to achieve.

What should the "correct function" do?

The id field of a model is already incremental. Do you simply want to
append that to a string and what do you want to do with that string?

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...@googlegroups.com.

Anselme SERI

unread,
May 27, 2020, 7:35:04 AM5/27/20
to django...@googlegroups.com

Hello,

I will try to explain it to you in the language I understand best and I hope that you will have an excellent translator to identify me.

english version
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?

french version
Ce que je souhaite faire, c'est remplir le champ 'code' de mon modele 'Diplôme'. Par exemple le premier enregistrement du modèle aura la valeur 'BAC00001' dans le champ 'code', le deuxième 'BAC00002',...., 'BAC01653'.... .
L'approche que j'ai retenue pour atteindre ce objectif consiste à   définir une fonction dans le modèle qui va récupérer la valeur du dernier id du dernier enregistrerment, l'incrémenter puis la concatener à la chaine pour obtenir la valeur du champ code du nouvelle enregistrement. code = chaine + (lastid + 1) avec chaine = 'BAC000..'. J'espère que c'est clair maintenant?

Best regards

Anselme S.



To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/f8725fd3-bf12-4b82-b1d6-e8569d7220ff%40googlegroups.com.

Kasper Laudrup

unread,
May 27, 2020, 8:22:41 AM5/27/20
to django...@googlegroups.com
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

Akinfolarin Stephen

unread,
May 27, 2020, 9:08:18 AM5/27/20
to Django users
i feel in your last session you are trying to concatenate a string and an integer use the int function to convert it to string then the number will show

Anselme SERI

unread,
May 27, 2020, 10:31:37 AM5/27/20
to django...@googlegroups.com

When I test the function you offer 'self.id' returns 'None'

--
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...@googlegroups.com.

Anselme SERI

unread,
May 27, 2020, 10:34:10 AM5/27/20
to django...@googlegroups.com

the error message is
unsupported format string passed to NoneType.__format__

Le mer. 27 mai 2020 à 13:09, Akinfolarin Stephen <akinfolar...@gmail.com> a écrit :
--

Derek

unread,
May 29, 2020, 2:07:13 AM5/29/20
to Django users
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.

Anselme SERI

unread,
May 29, 2020, 6:43:19 AM5/29/20
to django...@googlegroups.com
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.

--
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...@googlegroups.com.

Derek

unread,
May 29, 2020, 10:30:51 AM5/29/20
to Django users
I would not assume what "previous" means. Rather use post_save to get the actual ID of the current recording.
To unsubscribe from this group and stop receiving emails from it, send an email to django...@googlegroups.com.
Reply all
Reply to author
Forward
0 new messages