Django: get object's random atribute
这是我的模型课:
1 2 3 4 5 6 7 8 9 10 11 12 | class Player(models.Model): name = models.CharField(max_length=50) photo = models.ImageField() games = models.IntegerField() minutes = models.IntegerField() points = models.IntegerField() assists = models.IntegerField() rebounds = models.IntegerField() steals = models.IntegerField() def __unicode__(self): return self.name |
我想随机展示其中一个属性。最好的方法是什么?
基于Django:获取模型字段列表?如何从列表中随机选择一个项目?你可以这样写:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | import random class Player(models.Model): name = models.CharField(max_length=50) photo = models.ImageField() games = models.IntegerField() minutes = models.IntegerField() points = models.IntegerField() assists = models.IntegerField() rebounds = models.IntegerField() steals = models.IntegerField() def random_field(self): return random.choice([f.name for f in self._meta.get_fields()]) |