简体   繁体   中英

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.

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. 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. So there would be 100 instances. Level 100 would be the max level.

In addition, the xp_threshold would increment by 50% each level.

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.

I don't particular care how the numbers are rounded.

I'm using 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.

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.

Any ideas?

Thanks!

It is about Python not Django. Simply you can't do this in Python

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

this will throw throw NameError on 4. line

Instead use shell to create data like so python manage.py shell

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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