从my views.py Django中的我的选择中获取标签

2024-05-20 17:21:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个模型,其中一个字段是指定的颜色

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')

我的问题是,当我想在我的views.py中获取模型数据时,因为我正在执行以下操作

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

这个返回decolor id,我更喜欢颜色的名称。在阅读一些帖子时,我知道我必须使用.choices,但我不确定在哪里。有人能帮我吗

多谢各位


Tags: 模型idtrue颜色modelslengthmaxgateway
1条回答
网友
1楼 · 发布于 2024-05-20 17:21:26

你看here
改变

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

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

您可以使用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)

要显示值,请使用:

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

相关问题 更多 >