Note that there are some explanatory texts on larger screens.

plurals
  1. POUsing an object's method to sort a list of objects that contains the object
    text
    copied!<p>I have a problem. </p> <p>I am trying to generate a list of objects of different types sorted by the object's "date". Each object has a method <code>getDate</code> which returns the date to sort by. </p> <p>The <code>UserProfile</code> object contains a method <code>recent_activity</code> which should return this sorted list of objects. </p> <p>However, see the line <code>#items.append(self)</code> in the below? </p> <pre><code>class UserProfile(models.Model): ... def getDate(self): return self.last_edited ... def recent_activity(self): followed = ... sponsored = ... ... items = [] #items.append(self) #&lt;-- If this is in, the call to sorted doesn't work for f in followed: if (...): items.append(f) for s in sponsored: if (...): items.append(s) for c in comments: if (...): items.append(c) for u in updates: if (...): items.append(u) for p in projects: items.append(p) #return items[0:7] #&lt;-- If this is in, everything is fine! items = sorted(items, key=lambda item: item.getDate(),reverse=True) return items[0:7] </code></pre> <p>When I comment out the line <code>items.append(self)</code>, the code as written works perfectly, returning a (sliced) list of objects of different types sorted by date (using the <code>getDate()</code> method).</p> <p>However, when this line is included, the code works intermittently - and I mean that for some objects it works (as above), and for some it does not (at all - in fact it often simply returns None).</p> <p>If I return the array BEFORE calling <code>sorted</code>, again, everything works fine. So the problem is associated with the call to <code>sorted</code>. </p> <p>Looking forward to hearing what I'm doing wrong!</p> <p>(Just to be clear, someone has down-rated this question, I have no idea why - if you think it's unclear, please take the time to comment so I can improve the question!). </p> <p><strong>Edit</strong> - Now fixed. Solution was having occasional <code>getDate()</code> calls returning <code>datetime.date</code> objects rather than <code>datetime.datetime</code> objects because of a database migration causing me to manually populate some of the fields with the wrong type of object. Bit surprised to see no exceptions appear, just silent failing.</p>
 

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