虽然您发布的解决方案“有效”,但它是一种非常 PHP 的做事方式。
一种更 Django 的方式:
在应用程序的 models.py 文件中:
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) < 1:
self.string = RandomWordString.generate(3)
super(RandomWordString, self).save(*args, **kwargs)
然后,从任何视图或其他任何地方:
from words.models import RandomWordString
seq = RandomWordString.generate(3)
因为我们覆盖了保存,我们也可以这样做:
from words.models import RandomWordString
string = RandomWordString.objects.create()
string.save()
这将所有逻辑都放在模型本身中,这比将其放在视图中略好(尽管这完全是个人喜好问题)。
除了我发布的内容之外,您还需要向 RandomWordString.generate 添加一些逻辑,以确保您不会无限循环。