Say I have an extremely simple model that is just a list of words:
class WordList(models.Model):
word = models.CharField(max_length=60)
After a user submits a form, I want to...
I know how to get four random words:
WordList.objects.order_by('?')[:4]
I know how to make this a context and return it to a template, at which point I can do whatever with it, but I'm stumped on how I do this behind the scenes so I can do the rest of my stuff before returning it to the user. The final string should look like this:
these-are-my-words
Furthermore, where in my app do I do this? I come from PHP and there, I would have a functions.php
file or something to perform backend stuff and keep it out of the presentation. I've found a few other posts from people stating they use a functions.py
, but I'm not sure how to include external pages that aren't in the same folder as the existing views.py
. If I do:
from functions import myfunc
It only works if functions.py
is in the folder as wherever I am importing it from.
To turn your queryset into a string, use python's join function.
your_string = '-'.join([str(i) for i in WordList.objects.order_by('?')[:4]])
I suspect that this code should actually live in one of your views and never touch your database, but that's hard to say without knowing what your app is doing. (Surely you're passing this string to a template and rendering it onto an html page?)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With