简体   繁体   中英

Obtain the label from my choices in my views.py - Django

I have a model where one of the fields is the color assigned.

class Gateway(models.Model):
    colors = (
        ('0','Black'), ('1','White'), ('2','Blue'), ('3','Red'),
        ('4','Green'), ('5','Brown'), ('6','Grey'), ('7','Pink'),
        ('8','Purple'), ('9','Orange'), ('10','Yellow'),('11','Darkolive'),
        ('12','Lightpink'),('13','Lightblue'),
    )

    gat_id = models.CharField(max_length=16, primary_key=True, unique=True)
    gat_name = models.CharField(max_length=20, unique=True)
    gat_lat = models.FloatField()
    gat_lon = models.FloatField()
    gat_color = models.CharField(max_length=5, choices=colors, default='Black')

My problem is when I want to obtain the model data in my views.py , because I'm doing the following,

gateways = Gateway.objects.all()
gateways = loads(serializers.serialize('json', gateways))

And this return de color id and I prefer the name of the color. Reading some posts I understand I have to use .choices but I'm not sure where. Can somebdoy help me please?

Thank you very much

You Look at here
and change

gat_color = models.CharField(max_length=5, choices=colors, default='Black')

To

gat_color = models.CharField(max_length=2, choices=colors, default='0')

OR

You can use IntegerField

class Gateway(models.Model):
    colors = [
        (0,'Black'), (1,'White'), (2,'Blue'), (3,'Red'),
        (4,'Green'), (5,'Brown'), (6,'Grey'), (7,'Pink'),
        (8,'Purple'), (9,'Orange'), (10,'Yellow'),(11,'Darkolive'),
        (12,'Lightpink'),(13,'Lightblue'),
    ]

    gat_id = models.CharField(max_length=16, primary_key=True, unique=True)
    gat_name = models.CharField(max_length=20, unique=True)
    gat_lat = models.FloatField()
    gat_lon = models.FloatField()
    gat_color = models.IntegerField(choices=colors, default=0)

To Display Value use:

gateway = Gateway.objects.all()[0]
gateway.get_gat_color_display()
>>> return 'Black'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM