-2

Here is my model class:

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

I want to show one of these atributes randomly. What is the best way to do so?

Cœur
  • 34,719
  • 24
  • 185
  • 251
Irmantas Želionis
  • 2,032
  • 3
  • 15
  • 27

1 Answers1

0

based on Django: Get list of model fields? and How to randomly select an item from a list? you might write up something like that:

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()])
Community
  • 1
  • 1
dahrens
  • 3,769
  • 1
  • 19
  • 36