Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combining queryset into single string with Django

Tags:

python

django

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...

  • Retrieve four random words
  • Combine them into a single string
  • Ensure a duplicate string has not been previously generated and if so, run it again
  • Save that to the database when it's good
  • Return the result to the user.

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.

like image 264
subvertallchris Avatar asked Feb 24 '13 18:02

subvertallchris


1 Answers

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?)

like image 66
Aidan Ewen Avatar answered Oct 06 '22 18:10

Aidan Ewen