how to create an auto incrementing integer field that is not a primary key in Django

Viewed 638

I am creating a Django webapp to automate the filling of a certain paper form. Each form has to have a unique form number that is made up of a prefix, a year, and an increment (which resets every year), like "Form ABC-2017-0001". I don't want to make this unique form number the primary key, but Django only allows one AutoField per model.

Here's what I've tried:

class Form(models.Model):
    prefix = 'ABC'
    year = models.CharField(max_length=4)
    increment = models.AutoField(primary_key = False)
    form_number= prefix + '-' year + '-' increment

Django says:

AssertionError: A model can't have more than one AutoField.

Edit 10/15/17

Ok, so after a bit more work, the following has occurred to me: make a function that queries how many objects for a given year we already have in the database, adds one to the value, and then returns a string that incorporates this info.

class Form(models.Model):  

    year = models.CharField(max_length=4)
    form_number = get_form_number(year)

    def get_form_number(year):
        prefix = 'ABC' 
        increment = Form.objects.filter(year = year).count() + 1
        form_number = prefix + '-' + str(year) + '-' + str(increment).zfill(4)
        return form_number

Unfortunately code like this is giving me

NameError: name 'Form' is not defined

Anybody have an idea why the function called from within a Form can't figure out what a Form is?

0 Answers
Related