-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
  • 37,241
  • 25
  • 195
  • 267
Irmantas Želionis
  • 2,194
  • 3
  • 17
  • 30

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,879
  • 1
  • 20
  • 38