Question

I have an object:

POP_CULTURE_TYPES = (
    ('SG','Song'),
    ('MV', 'Movie'),
    ('GM', 'Game'),
    ('TV', 'TV'),
)

class Pop_Culture(models.Model):
      name = models.CharField(max_length=30, unique=True)
      type = models.CharField(max_length=2, choices = POP_CULTURE_TYPES, blank=True, null=True)

Then I have a function:

def choice_list(request, modelname, field_name):
     mdlnm = get.model('mdb', modelname.lower())
     mdlnm = mdlnm.objects.values_list(field_name, flat=True).distinct().order_by(field_name)
     return render_to_response("choice_list.html", {
           'model'  : modelname,
           'field'  : field_name,
           'field_list'  : mdlnm })

This gives me a distinct list of all the "type" entries in the database in the "field_list" variable passed in render_to_response. But I don't want a list that shows:

SG

MV

I want a list that shows:

Song

Movie

I can do this on an individual object basis if I was in the template

object.get_type_display

But how do I get a list of all of the unique "type" entries in the database as their full names for output into a template?

I hope this question was clearly described. . .

Was it helpful?

Solution

How about something like this at the end of your choice_list()?

def choice_list(request, modelname, field_name):
    # ...
    pct = dict(POP_CULTURE_TYPES)
    return [pct[key] for key in mdlnm]

Or in one line w/o the dict() call:

    return [pct[1] for pct in POP_CULTURE_TYPES if pct in mdlnm]

Not pretty but it will work until to run across something better.

OTHER TIPS

You could use:

OBJECT.get_FIELD_display()

Example:

content = Pop_Culture.objects.get(...)

ctype = content.get_type_display()

There is no need for workarounds :)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top