SitePoint Sponsor

User Tag List

Results 1 to 4 of 4
  1. #1
    SitePoint Member
    Join Date
    Sep 2013
    Posts
    17
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Python+DJango Dictionary loser its "order" in template.

    I'm trying to loop through a queryset to built a dictionary, then loop through that dictionary in my template to create a grid. It works, BUT, the fields are in the wrong order. Instead of getting them in the order of Field1 Field2 Field3, I get Field2, Field1, Field3. This is just an example of whats happening. In actuality I have 10 fields, but they're not rendered in the same order I defined the model with. Can anyone help explain why and what I can do to fix so that the order stays consistent?

    models.py:
    Code Python:
    class MyModel(models.Model)
        Field1 = models.CharField(max_length=30)
        Field2 = models.DateTimeField()
        Field3 = models.CharField(max_length=30)

    views.py:
    Code Python:
    def MyView(request):
        MyQuerySet = MyModel.objects.all()[:10]
        MyDictionary = {}
        RowNumber = 0
        for row in MyQuerySet:
            NestedDictionary = {}    
            ColumnNumber = 0    
            for column in row._meta.fields:
                if  column.verbose_name != "ID":
                    fieldtype = str(type(column)).replace("'>", "").replace("<class 'django.db.models.fields.", "")
                    NestedDictionary.update({str(ColumnNumber):
                                {'name': column.verbose_name,
                                'value': getattr(row, column.verbose_name),
                                'type': fieldtype}
                                })
                    ColumnNumber = ColumnNumber + 1
            MyDictionary.update({str(RowNumber): NestedDictionary})
            RowNumber = RowNumber + 1
        ctx = {}
        ctx.update({'MyDictionary':MyDictionary})
        return render_to_response('MyTemplate.html', ctx, context_instance=RequestContext(request))

    MyTemplate.html:
    Code Python:
    <table cellpadding="1px" cellspacing="1px" border="1px">
    {% for key, row in MyDictionary.items %}
        <tr>        
            {% for key2, field in row.items %}
                <td>
                    {{ field.value }}
                </td>
            {% endfor %}
        </tr>
    {% endfor %}
    </table>

  2. #2
    SitePoint Member
    Join Date
    Sep 2013
    Posts
    17
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I have an update: I just found this information on the custom data structure class "SortedDict" :
    https://code.djangoproject.com/wiki/SortedDict

    That helps move me in the right direction, BUT, it still doesn't solve my problem. And thats because when I hit the line that reads "for column in row._meta.fields:", it loops through the queryset fields in an order that is not consistent with which they were actually defined in my model. That stinks because I would have thought they'd have been in original order when selecting all of them at once. So its probably happening when I hit "MyQuerySet = MyModel.objects.all()[:10]"

    Is there any way to ensure that the fields in the queryset remain in the order which the model was defined without explicitly requesting each field one at a time?

  3. #3
    SitePoint Member
    Join Date
    Sep 2013
    Posts
    17
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Ok final update. I was wrong. The queryset was returning the fields in the correct order.

    I ended up using SortedDict as previously mentioned, and then used a custom filter in my template as described here:
    http://stackoverflow.com/questions/2...ct-in-template

    That did the trick.

  4. #4
    SitePoint Addict
    Join Date
    Aug 2013
    Location
    New Zealand
    Posts
    302
    Mentioned
    5 Post(s)
    Tagged
    0 Thread(s)
    There is a Meta option you can add to your model called "ordered" (if memory serves. Then when you use the QuerySet all() method they come out in that order. Other than that and if you don't need to do it in the template you can use the QuerySet order_by() method.

    Sent from my XT316 using Tapatalk 2


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •