5

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.

2
  • you can use this approach stackoverflow.com/a/2224964/3033586 and abstract from using numbers in your queryset ... if doesn't help - edit your question, because it's unclear what you want, maybe add queryset where you have problems Commented Jul 10, 2015 at 6:34
  • Seems as duplicate of stackoverflow.com/questions/9674860/… Commented Jul 10, 2015 at 7:36

2 Answers 2

2

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'
Sign up to request clarification or add additional context in comments.

1 Comment

this works well single object.Please look @ my question edit
0

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.

4 Comments

how can I include these labels in values() method?
You don not need to call the values, as the default display value will be "pass"/"fail".
The display values will be either "pass"/"fail" but the values saved in the db will be "1"/"2" i.e depending upon the choices
Sorry I didn't get you.I was saying about obtaining display values in values query set.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.