1

I am using DRF and have a couple models where I want to generate unique numbers separate from ID's. For example, one model would have a number like PRJ023400 and another would be TSK2949392.

I created a utility function to generate random numbers and as the field and attempted to use this function as the default.

number = models.CharField(max_length = 10,
                          blank=True,
                          editable=False,
                          default='PRJ'+create_new_ref_number())

The problem I am facing is that this only generates a new string when running a migration. What would be the best approach to make this work?

Cheers!

2 Answers 2

3

default can accept a function. As per the documentation:

The default value for the field. This can be a value or a callable object. If callable it will be called every time a new object is created.

Considering all this you can set it to a function like this:

def number_default_function():
    return 'PRJ' + create_new_ref_number()

class YourModel(models.Model):
    number = models.CharField(
        max_length = 10,
        blank=True,
        editable=False,
        default=number_default_function
    )
Sign up to request clarification or add additional context in comments.

2 Comments

I tried this out but unfortunately it returned the same results.
@PixelsOfMind your previous approach failed because default='PRJ'+create_new_ref_number() was evaluated when the line was evaluated, i.e. default was set to 'PRJ<SOMETHING>', If the approach in my answer fails that means that your function create_new_ref_number returns the same thing for some reason.
1

I was actually able to figure this out.

For the model field, I changed it to:

number = models.CharField(max_length = 10,
                              blank=True,
                              null=True,
                              editable=False)

When saving, I added this function to generate a new string each time:

def save(self, *args, **kwargs):
        self.number = 'PRJ' + create_new_ref_number()
        super(Project, self).save(*args, **kwargs)

Hopefully this can help someone else out.

Cheers.

1 Comment

In passing, it's worth being careful if number is user-visible, since it leaks information about how many objects you have and the rate of object creation. That may not be desirable.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.