As long as your published solution "works", this is a very easy way to PHP.
Another Django way:
In your models models.py file:
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)
Then from any view or anywhere else:
from words.models import RandomWordString seq = RandomWordString.generate(3)
Since we overloaded the save, we can also just do:
from words.models import RandomWordString string = RandomWordString.objects.create() string.save()
This puts all the logic in the models themselves, which is slightly better than having it in the view (although this is completely a matter of taste).
In addition to what I posted, you will also want to add some logic to RandomWordString.generate to make sure you are not looping endlessly.
source share