开发者

List display names from django models

开发者 https://www.devze.com 2022-12-23 19:58 出处:网络
I have an object: POP_CULTURE_TYPES = ( (\'SG\',\'Song\'), (\'MV\', \'Movie\'), (\'GM\', \'Game\'), (\'TV\', \'TV\'),

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())
   开发者_如何学Python  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. . .


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.


You could use:

OBJECT.get_FIELD_display()

Example:

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

ctype = content.get_type_display()

There is no need for workarounds :)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号