Opened 15 years ago

Closed 15 years ago

#10150 closed (invalid)

Make model_to_dict use SortedDict

Reported by: Rob Hudson <treborhudson@…> Owned by: nobody
Component: Forms Version: 1.0
Severity: Keywords:
Cc: treborhudson@… Triage Stage: Unreviewed
Has patch: yes Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

The particular use case I have for this is wanting to take a model object, convert it to a dictionary, and use that dictionary in a detail template. Since I'm displaying it in a template, I'd like the order to match that of the model (and forms based on the model). And it makes sense that this function name model_to_dict should maintain model ordering for its fields.

Attachments (1)

model_to_sorted_dict.diff (500 bytes ) - added by Rob Hudson <treborhudson@…> 15 years ago.
One line patch that replaces uses SortedDict in favor of {}

Download all attachments as: .zip

Change History (5)

by Rob Hudson <treborhudson@…>, 15 years ago

Attachment: model_to_sorted_dict.diff added

One line patch that replaces uses SortedDict in favor of {}

comment:1 by Rob Hudson <treborhudson@…>, 15 years ago

Cc: treborhudson@… orzel@… added
Has patch: set

comment:2 by Rob Hudson <treborhudson@…>, 15 years ago

Cc: orzel@… removed

Didn't mean to add orzel... that was a browser autocomplete fail. Sorry!

comment:3 by Rob Hudson <treborhudson@…>, 15 years ago

More context of why this is useful...

Similar to iterating over fields in a Form or ModelForm, you could use the model_to_dict method for a template (or email, etc.) like so:

def profile_detail(request, profile_id):
    try:
        profile = Profile.objects.get(pk=profile_id)
    except Profile.DoesNotExist:
        raise Http404
    return render_to_response('profiles/detail.html', {
        'profile': profile,
        'profile_data': model_to_dict(profile, exclude=('last_modified',))
    })

In the template you'd then have something you can iterate:

<dl>
{% for key, value in profile_data.items %}
    <dt>{{ key }}</dt>
    <dd>{{ value }}</dd>
{% endfor %}
</dl>

With model_to_dict not using SortedDict, the items come out in an unknown order, which isn't useful for this purpose.

I plan on running the test suite to make sure this change doesn't break any tests, and adding some docs where appropriate.

comment:4 by Rob Hudson <treborhudson@…>, 15 years ago

Resolution: invalid
Status: newclosed

After a discussion on the django-dev IRC channel, this isn't the correct solution for the goal. I'm closing this ticket as invalid.

Note: See TracTickets for help on using tickets.
Back to Top