1

So I am developing a Django app and what I want at the moment in to develop a script that selects a random field from a row with 3 words in a MySQL database that I have. I have searched for info but haven't managed how to do it.

My database:

enter image description here

What I want is the script to read the database and select a random word each time. I haven't worked so much with DBs in Python so I have no clue about how to do it. Help is much appreciated.

1 Answer 1

1

You can use random.choice like this:

import random

columns = ['word1', 'word2', 'word3']
chosen_column = random.choice(columns)

#now access DB using chosen_column for example:
Your_model.objects.raw('SELECT ' + chosen_column + ' FROM myapp_yourmodel')
Sign up to request clarification or add additional context in comments.

6 Comments

Okay thanks, when you mean access the DB using chosen_column what do you mean? Do I have to create a connexion with the MySQL database first?
If you're using Django, you probably can use the model so you don't have to specifically create a connection. I'll edit my answer with an example
Wouldn't it be smarter to choice() after getting the data?
I imagine I'll have to do that in the view I'm rendering, don't I? @Gamopo
Sure! Or wherever you want to use it
|

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.