Rajan
Rajan

Reputation: 73

Creating new objects under specific parameters

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?

Upvotes: 1

Views: 74

Answers (1)

Mohith7548
Mohith7548

Reputation: 1360

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)

Upvotes: 1

Related Questions