Home > Back-end >  How to best pass converted values of a Django model to context?
How to best pass converted values of a Django model to context?

Time:09-16

I have a model Poller that has a bunch of integer fields. I have a function convert_thousands that converts integer figures into short strings like so:

convert_thousands(1300000) # Returns '1,3 m' etc.

How to best convert alle of the integer fields and pass them into the context? Right now I'm doing it one by one by one..:

Foo = convert_thousands(poller.integerfield_one)
Bar = convert_thousands(poller.integerfield_two)
[..]

    context = {
        'poller': poller,
        'Foo': Foo,
        'Bar': Bar
        [..]
    }

Desired outcome would look s.th. like

[..]
    context = {
        'poller': poller,
        'converted_strings': converted_strings
    }

# and render in the template by {{ converted_strings.integerfield_one }}

CodePudding user response:

You can use dictionary comprehension here:

data = {
    'Foo': poller.integerfield_one,
    'Bar': poller.integerfield_two
}

# …

context = {
    'poller': poller,
    'converted_strings': { k: convert_thousands(v) for k, v in data.items() },
    # …
}

or if you want these in the context (and thus not in a specific item converted_strings, we can work with dictionary unpacking:

data = {
    'Foo': poller.integerfield_one,
    'Bar': poller.integerfield_two
}

# …

context = {
    'poller': poller,
    **{ k: convert_thousands(v) for k, v in data.items() },
    # …
}

Then you thus can render this with {{ Foo }} and {{ Bar }}.

  • Related