javis_mcqueen
javis_mcqueen

Reputation: 181

How can I return display values for all selected fields and field names in QuerySet?

I have a Django view that passes templated data to an html page as json. The issue I am having is that the actual database fields and fieldnames are passed instead of the human-readable name and result of get_FOO_display(), respectively. For clarity, here is what my model looks like:

class FooBar(models.Model):
    name = models.CharField('Name', max_length=255)
    AWAITING_CLASSIFICATION_STATUS = 1
    IN_PROGRESS_STATUS = 2
    AWAITING_REVIEW_STATUS = 3
    CLOSED_STATUS = 4
    STATUS_CHOICES = [
        (AWAITING_CLASSIFICATION_STATUS, 'Awaiting Classification'),
        (IN_PROGRESS_STATUS, 'In Progress'),
        (AWAITING_REVIEW_STATUS, 'Awaiting Review'),
        (CLOSED_STATUS, 'Closed')
    ]
    status = models.IntegerField('Status', choices=STATUS_CHOICES, default=AWAITING_CLASSIFICATION_STATUS)

And my view currently:

def IndexView(request):
    foo_list = FooBar.objects.all().values()
    json_list = json.dumps(list(foo_list))
    context = {'foo_list': json_list}
    return render(request, 'foo-app/index.html', context)

What my data looks like:

[
  {'name': "name1", "status": 1},
  {'name': "name2", "status": 2},
]

And what my data should look like:

[
  {'Name': "name1", "Status": "Awaiting Classification"},
  {'Name': "name2", "Status": "In Progress"},
]

Some ideas I have explored:

  1. Iterating over the list and looking up each based on the model (sounds like a lot of extra processing server side).
  2. Sending the QuerySet in its entirety and processing it client side (I think this would include more data than I would like to reveal to the client).
  3. Storing the data in the database in human readable form (nope).

What is the most Pythonic/Djangonic way of doing this?

Upvotes: 0

Views: 30

Answers (1)

Greg Cowell
Greg Cowell

Reputation: 693

Option 2 would be the usual way to do it. You would be passing the data to the Django template engine - not the client directly. It's up to you to determine the data that the client/browser actually sees by coding your Django template appropriately.

Upvotes: 1

Related Questions