0

I am a beginner in Django as well as Python.

I first generate 50 random numbers and store them in a list and then in a text field in model User.

def generate(request, user_id):
    easy = [] * 55
    cnt = 0
    while cnt < 50:
        random_id = random.randint(1, 200)
        if random_id not in easy:
            easy.append(random_id)
            cnt += 1
    current_user = User.objects.get(pk=user_id)
    current_user.question_array = json.dumps(easy)
    return render(request, 'comp/question.html', {'easy': easy[0], 'question_id': 1,'user_id':user_id})

But when I try to retrieve the value from field I get only 0.

When I try to use it as a list it shows an error of "int object cannot be subscript".

This is the code to retrieve it:

def next(request,user_id, question_id):
    current_user = User.objects.get(pk=user_id)
    jsonDec = json.decoder.JSONDecoder()
    easy = jsonDec.decode(current_user.question_array)
    return render(request, 'comp/question.html',
                  {'easy': easy, 'question_id': int(question_id) + 1,'user_id':user_id})

I have used the answer to this question given by mindthief to store a list in a table.

Edit:

My main problem is that the list is not getting stored in database. Any ideas why?

bouteillebleu
  • 2,456
  • 23
  • 32
Sniper
  • 1,428
  • 1
  • 12
  • 28

1 Answers1

0

You need to add a .save() call to save the data to the db:

current_user = User.objects.get(pk=user_id)
current_user.question_array = json.dumps(easy)
current_user.save()
...

BTW, you can also use random.sample():

easy = random.sample(range(200), 50)  # in python 2.x use xrange() 

and json.loads():

easy = json.loads(current_user.question_array)

If you use PostgreSQL (highly recommended) you can even use a JsonField.

And finally, if the questions are stored in another model (Question), consider using a ManyToManyField instead.

Udi
  • 29,222
  • 9
  • 96
  • 129
  • i don't know much about database. Just started learning from youtube from thenewboston django tutorials. So dont know anything about sqlite3 or PostgresSQL. Thanks for random.sample really helped me reduce the code! – Sniper Dec 17 '16 at 16:21