简体   繁体   English

如何使用for循环手动将对象添加到Django模型?

[英]How to manually add objects to a Django model using a for loop?

relatively new to Python and very new to Django so looking for some help with this. 对Python而言相对较新,而对Django而言则相对较新,因此需要一些帮助。

I'm trying to create a user rank-up system similar to what you'd find in an role-playing game (ie the user gains levels by getting experience points) 我正在尝试创建一个与角色扮演游戏中类似的用户升级系统(即,用户通过获得经验值来获得等级)

So far I have an app in my project with this simple model within its models.py. 到目前为止,我在我的项目中有一个应用程序,该应用程序的models.py中包含此简单模型。 I've already ran migrations and this currently empty table is sat in my database: 我已经进行了迁移,并且此当前为空的表位于我的数据库中:

class UserLevel(models.Model):
    level_rank = models.IntegerField()
    xp_threshold = models.IntegerField()

Now what I want to do is add levels 1 to 100 (integers) to level_rank. 现在我要做的是将级别1到100(整数)添加到level_rank。 So there would be 100 instances. 因此,将有100个实例。 Level 100 would be the max level. 最高等级为100。

In addition, the xp_threshold would increment by 50% each level. 另外,xp_threshold将每级增加50%。

So for example, level 1 would have an xp_threshold of 100, level 2 would have 150, level 3 would have 225 and so on. 因此,例如,级别1的xp_threshold为100,级别2的值为150,级别3的值为225,依此类推。

I don't particular care how the numbers are rounded. 我不在乎数字如何取整。

I'm using Django v2.0.13 我正在使用Django v2.0.13

So far, I have this: 到目前为止,我有这个:

class UserLevel(models.Model):
    level_rank = models.IntegerField()
    xp_threshold = models.IntegerField()

    levels_range = range(1,101)

    for level in levels_range:
        UserLevel.objects.create(level_rank=level)

But this is giving me a NameError saying that UserLevel is not defined. 但这给了我一个NameError,说UserLevel没有定义。

I know I could manually just pump this data into Django's admin but that's going to take a looooong time for 100 levels and I know there's a better way to do this. 我知道我可以手动将这些数据泵送到Django的管理员中,但是要花100个级别才能花费很长时间,而且我知道有一个更好的方法。

Any ideas? 有任何想法吗?

Thanks! 谢谢!

It is about Python not Django. 这是关于Python而不是Django。 Simply you can't do this in Python 简而言之,您无法在Python中做到这一点

class MyAwesomeClass:
    a = 1
    print(a)
    print(MyAwesomeClass.a)

this will throw throw NameError on 4. line 这将在第4行上抛出NameError

Instead use shell to create data like so python manage.py shell 而是使用shell创建数据,例如python manage.py shell

from yourapp.models import UserLevel
UserLevel.objects.bulk_create([UserLevel(level_rank=level) for level in range(1, 101)])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM