简体   繁体   中英

Django foo_display with values()

Lets say I have a django Model shown below

 Class Student(models.Model):
     name=models.CharField(max_length=100);
     status=models.IntegerField()

status field will only have values 1,2. Is there some way I can replace 1,2 with their corresponding display values say (pass,fail) every time i use them in values() method without iterating further over the queryset. eg:

something like this

Student.objects.values(staus_display_value)

so that this returns a value queryset with display values instead of db values

[{"name":"jane","status":"pass"},
{"name":"john","status":"fail"}] 

I know that Model.get_FOO_display() can be used to get display values for individual objects.

Try this

class Student(models.Model):
    X_CHOICES = (
            (1, 'Pass'),
            (2, 'Fail'),
        )
    name=models.CharField(max_length=100);
    status = models.IntegerField(default=1,choices=X_CHOICES)

>>>Student.objects.create(name="myname")
>>>s = Student.objects.get(name="myname")
>>>s.get_status_display()
'Pass'

Yes, you can do the following in your model:

Class Student(models.Model):
    X_CHOICES = (
            (u'1', u'Pass'),
            (u'2', u'Fail'),
        )
    name=models.CharField(max_length=100);
    status = models.IntegerField(default=1,choices=X_CHOICES)

Hope this helps.

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