1

I am new to django and trying to understand the capabilities of django models. I stumbled across Model managers and understand that they can be used to perform customized queries and I understand how they serve that function.

But what if I wanted to create a new object but under a specific set of guidelines. For example let's say I had a model as such:

#models.py
class TestModel(model.Model):
    num = models.IntegerField(default=5)

Now if I create a new object without specifying the value of num it will set its default equal to 5. But is it possible to have a creation function within the model that would give it another value. For example what if I wanted the value to be a random number between 1 and 100. I know that I could always run that function and then set the num field equal to its output and then create the new object, but I want to have that function run within the model and execute just by calling TestModel(). Is this possible?

1 Answer 1

1

As you know there are multiple ways to produce random integers like using random, numpy etc., packages. But there is also a package called uuid stands for Universally Unique IDentifier, that produces random 128 bytes ids on the basis of time, Computer hardware (MAC etc.).

When you use all those methods to produce random numbers in regular python programs, they'll work perfectly fine. But when you use them in Django models each of them gives the same output no matter how many time you run.

I have discovered this workaround,

import uuid, random

class MyModel(models.Model):

    def get_random_integer():
        id = uuid.uuid4()
        # id.int is a big number, use some logic to get number in range of 1 to 100
        random.seed(id.int)
        return random.randrange(1, 100)

    num = models.IntegerField(default=get_random_integer)

Sign up to request clarification or add additional context in comments.

3 Comments

No this will not work. You will still always get the same number, because you are calling the method at import time. You need to pass the callable, not the result; default=get_random_integer.
@DanielRoseman Thanks for pointing out. I've modified the answer. Now, I've tested and it works.
Please upvote if you find useful! so that more people can easily get benefitted

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.