在特定参数下创建新对象 [英] Creating new objects under specific parameters

查看:57
本文介绍了在特定参数下创建新对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是django的新手,并试图了解django模型的功能。我偶然发现了模型管理器,并了解它们可用于执行自定义查询,并且了解它们如何实现该功能。

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)

现在,如果我在不指定num值的情况下创建一个新对象,它将设置其默认值等于5。但是在模型中是否可以有一个创建函数来为其赋予另一个值。例如,如果我希望该值是介于1到100之间的随机数,那该怎么办?我知道我总是可以运行该函数,然后将num字段设置为等于其输出,然后创建新对象,但是我想要函数在模型中运行,并且仅通过调用TestModel()即可执行。

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?

推荐答案

如您所知,有多种方法可以生成随机整数,例如使用random,numpy等软件包。但是,还有一个名为 uuid 的软件包,表示 Universally Unique IDentifier (通用唯一IDentifier),该软件包会根据时间生成随机的128字节ID,计算机硬件(MAC等。)

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.).

当您使用所有这些方法在常规python程序中生成随机数时,它们会很好地工作。但是,当您在Django模型中使用它们时,无论您运行多少次,它们每个都将提供相同的输出。

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)

这篇关于在特定参数下创建新对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆