How to create a custom AutoField primary_key entry within Django

2024/4/15 2:20:49

I am trying to create a custom primary_key within my helpdesk/models.py that I will use to track our help desk tickets. I am in the process of writing a small ticking system for our office.

Maybe there is a better way? Right now I have:

id = models.AutoField(primary_key=True)

This increments in the datebase as; 1, 2, 3, 4....50...

I want to take this id assignment and then use it within a function to combine it with some additional information like the date, and the name, 'HELPDESK'.

The code I was using is as follows:

id = models.AutoField(primary_key=True)def build_id(self, id):join_dates = str(datetime.now().strftime('%Y%m%d'))return (('HELPDESK-' + join_dates) + '-' + str(id))ticket_id = models.CharField(max_length=15, default=(build_id(None, id)))

The idea being is that the entries in the database would be:

HELPDESK-20170813-1
HELPDESK-20170813-2
HELPDESK-20170814-3
...
HELPDESK-20170901-4
...
HELPDESK-20180101-50
...

I want to then use this as the ForeignKey to link the help desk ticket to some other models in the database.

Right now what's coming back is:

HELPDESK-20170813-<django.db.models.fields.AutoField>

This post works - Custom Auto Increment Field Django Curious if there is a better way. If not, this will suffice.

Answer

This works for me. It's a slightly modified version from Custom Auto Increment Field Django from above.

models.py

def increment_helpdesk_number():last_helpdesk = helpdesk.objects.all().order_by('id').last()if not last_helpdesk:return 'HEL-' + str(datetime.now().strftime('%Y%m%d-')) + '0000'help_id = last_helpdesk.help_numhelp_int = help_id[13:17]new_help_int = int(help_int) + 1new_help_id = 'HEL-' + str(datetime.now().strftime('%Y%m%d-')) + str(new_help_int).zfill(4)return new_help_id

It's called like this:

help_num = models.CharField(max_length=17, unique=True, default=increment_helpdesk_number, editable=False)

If gives you the following:

HEL-20170815-0000
HEL-20170815-0001
HEL-20170815-0002
...

The numbering doesn't start over after each day, which is something I may look at doing. The more I think about it; however, I am not sure if I even need the date there as I have a creation date field in the model already. So I may just change it to:

HEL-000000000
HEL-000000001
HEL-000000002
...
https://en.xdnf.cn/q/72994.html

Related Q&A

Multiple HoverTools for different lines (bokeh)

I have more than one line on a bokeh plot, and I want the HoverTool to show the value for each line, but using the method from a previous stackoverflow answer isnt working:https://stackoverflow.com/a/2…

Cant Install PIL 1.7

I have python 2.7.3 and I want to install PIL 1.7. I downloaded "PIL-1.1.7.win32-py2.7" and try to install it but it shows me an error messege that it cant find python 2.7 in the registry.&qu…

slice/split a layer in keras as in caffe

I have used this converter to convert a Caffe model to Keras. But one of my layers is of type slice and it needs to be converted as well but the converter currently does not support this and raises an …

Can I use regexes within datetime.strptime formats?

I have string values that contain a trailing time stamp. I thought I could use strptime with a regex pattern to extract those. Like:from __future__ import print_functionfrom datetime import datetime # …

Sort a list with longest items first

I am using a lambda to modify the behaviour of sort.sorted(list, key=lambda item:(item.lower(),len(item)))Sorting a list containing the elements A1,A2,A3,A,B1,B2,B3,B, the result is A,A1,A2,A3,B,B1,B2,…

Multivariate Root Finding in Python

Using excel solver, it is easy to find a solution (optimum value for x and y )for this equation: (x*14.80461) + (y * -4.9233) + (10*0.4803) ≈ 0However, I cant figure out how to do this in Python. The …

Python print not working when embedded into MPI program

I have an Python 3 interpreter embedded into an C++ MPI application. This application loads a script and passes it to the interpreter.When I execute the program on 1 process without the MPI launcher (s…

Detecting USB Device Insertion on Windows 10 using python

I cant get the following code for Detecting USB Device Insertion to work on my Windows 10 (64 bit) computer with Python 3.7.import win32serviceutil import win32service import win32event import servicem…

I get NotImplementedError when trying to do a prepared statement with mysql python connector

I want to use prepared statements to insert data into a MySQL DB (version 5.7) using python, but I keep getting a NotImplementedError. Im following the documentation here: https://dev.mysql.com/doc/con…

parsing transcript .srt files into readable text

I have a video transcript SRT file with lines in conventional SRT format. Heres an example:1 00:00:00,710 --> 00:00:03,220 Lorem ipsum dolor sit amet consectetur, adipisicing elit.2 00:00:03,220 --…