Note that there are some explanatory texts on larger screens.

plurals
  1. POCan't modify object by index in evaluated queryset with Django
    primarykey
    data
    text
    <p>I manage the order of <code>Documents</code> in a <code>Collection</code> by assigning ordinal numbers to <code>DocumentMemberships</code>, which is the model that represents an intersection of a <code>Document</code> and a <code>Collection</code>. Here is one place that I do this (this is inside a method of <code>Collection</code>):</p> <pre><code>memberships = self.membership_set.order_by('document__title', 'document__revision').all() for i in range(memberships.count()): if memberships[i].document.category == 'SDS': memberships[i].ordinal = i + 1000 # push documents in the 'SDS' category to the end else: memberships[i].ordinal = i # leave the rest ordered by title and then revision memberships[i].save() </code></pre> <p>However, when I inspect the <code>DocumentMemberships</code> in the admin interface after running this code, all the ordinals are zero (the default for that field). </p> <p>I tracked the issue down to the objects in the QuerySet not being properly modified when accessed by index. This is a shell session that more clearly demonstrates the issue:</p> <pre><code>&gt;&gt;&gt; memberships = s.membership_set.order_by('document__title', 'document__revision').all() &gt;&gt;&gt; memberships.all() [large number of DocumentMembership objects] &gt;&gt;&gt; memberships[0] [DocumentMembership object] &gt;&gt;&gt; memberships[0].ordinal = 2 &gt;&gt;&gt; memberships[0].ordinal 0 </code></pre> <p>The ordinals have to be fully computed as integers before further processing so I can't simply iterate over it. Did I miss something?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload