0

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 (i.e. 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!

1
  • 1
    You should do this in a migration file. Not in the model class (or at the bottom of that file). Especially since given this would succeed, it would each time create 100 UserLevels extra when you restart the server. Commented Apr 17, 2019 at 20:03

1 Answer 1

2

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)])
Sign up to request clarification or add additional context in comments.

1 Comment

Using the shell worked. Guess the next thing I need to learn is to how to run the django shell from a script, because refining the level and xp system will get fiddly otherwise. Thanks!

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.