Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>While your posted solution "works", it's a very PHP way of doing things.</p> <p>A more Django way:</p> <p>In your application's models.py file:</p> <pre><code>from django.db import models class Word(models.Model): word = models.CharField(max_length=60, blank=False, null=False, unique=True) def __unicode__(self): return u'%s' % self.word class RandomWordString(models.Model): string = models.CharField(max_length=255, blank=False, null=False, unique=True) def __unicode__(self): return u'%s' % self.string @staticmethod def generate(length): words = Word.objects.order_by('?')[:(length + 1)] possible_word_string = '-'.join(words.values_list('word', flat=True)) try: RandomWordString.objects.get(string=possible_word_string) # See if we've already generated this sequence return RandomWordString.generate(length) # Call ourselves again if we have except RandomWordString.DoesNotExist: return possible_word_string # If we haven't, return the value def save(self, *args, **kwargs): if not self.string or len(self.string) &lt; 1: self.string = RandomWordString.generate(3) super(RandomWordString, self).save(*args, **kwargs) </code></pre> <p>Then, from any view, or anywhere else:</p> <pre><code>from words.models import RandomWordString seq = RandomWordString.generate(3) </code></pre> <p>Because we overrode save, we can also just do:</p> <pre><code>from words.models import RandomWordString string = RandomWordString.objects.create() string.save() </code></pre> <p>This places all the logic within the models themselves, which is <em>slightly</em> better than having it in a view (though it's completely a matter of taste).</p> <p>Beyond what I've posted, you'd also want to add some logic to RandomWordString.generate to make sure you don't loop indefinitely.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload