Opened 7 years ago

Closed 7 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: UI/UX:


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@…> 7 years ago.
One line patch that replaces uses SortedDict in favor of {}

Download all attachments as: .zip

Change History (5)

Changed 7 years ago by Rob Hudson <treborhudson@…>

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

comment:1 Changed 7 years ago by Rob Hudson <treborhudson@…>

  • Cc treborhudson@… orzel@… added
  • Has patch set
  • Needs documentation unset
  • Needs tests unset
  • Patch needs improvement unset

comment:2 Changed 7 years ago by Rob Hudson <treborhudson@…>

  • Cc orzel@… removed

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

comment:3 Changed 7 years ago by Rob Hudson <treborhudson@…>

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):
        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:

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

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 Changed 7 years ago by Rob Hudson <treborhudson@…>

  • Resolution set to invalid
  • Status changed from new to closed

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