D_P
D_P

Reputation: 862

How to increase CharField by 1 in django?

Here I have some field like idnumber in my Profile model.Which will be the mix of integer, text and -. Everytime new profile registers I want to keep the - and text same but want to increase integer by 1. How can I achieve that ?

 user = get_object_or_404(get_user_model(), pk=pk)
    if request.method == 'POST':
        user_type = request.POST.get('type')
        user.profile.is_approved=True
        user.profile.save()
        if user_type == 'Some Type': # i got stuck here
            latest_profile = Profile.objects.filter(user_type='Some Type').last()
            user.profile.idnumber = latest_profile.idnumber + 1 #this will probably raise the error
            user.profile.save()

My model field for id number is like this

idnumber = models.Charfield(max_length=255,default="ABTX-123") 

ABTX- will be same but want to increase 123 to 124 if new profile registers

Upvotes: 1

Views: 65

Answers (1)

Manan M.
Manan M.

Reputation: 1394

You have to set idnumber as below...

idnumber = int(latest_profile.idnumber.split('-')[1]) + 1
new_idnumber = latest_profile.idnumber.split('-')[0] + '-' + str(idnumber)
user.profile.idnumber = new_idnumber

Upvotes: 1

Related Questions