Note that there are some explanatory texts on larger screens.

plurals
  1. POFinding objects according to related objects
    text
    copied!<p>I am trying to build a messaging application with Django. The reason I don’t use <code>postman</code> is that I need messaging between other objects than users and I don’t need most of the postman’s features.</p> <p>Here are my models:</p> <pre><code>class Recipient(models.Model): ... def get_unread_threads(): see below... class Thread(models.Model): author = models.ForeignKey(Recipient, related_name='initiated_threads') recipients = models.ManyToManyField( Tribe, related_name='received_thread', through='ThreadReading') subject = models.CharField(max_length=64) class Meta: app_label = 'game' class Message(models.Model): author = models.ForeignKey(Recipient, related_name='sent_messages') date_add = models.DateTimeField(auto_now_add=True) date_edit = models.DateTimeField(blank=True) content = models.TextField(max_length=65535) thread = models.ForeignKey(Thread) class Meta: get_latest_by = 'date' class ThreadReading(models.Model): thread = models.ForeignKey(Thread) recipient = models.ForeignKey(Recipient) date_last_reading = models.DateTimeField(auto_now=True) </code></pre> <p>My problem is about <code>get_unread_threads</code>. I can’t really find out how to do that. Here is a first try:</p> <pre><code>def get_unread_threads(self): """ return a queryset corresponding to the threads which at least one message is unread by the recipient """ try: query = self.received_thread.filter( message__latest__date_add__gt=\ self.threadreading_set.get(thread_id=F('id')).date_last_reading) except ObjectDoesNotExist: query = None return query </code></pre> <p>But obviously it doesn’t work because lookup can’t follow method <code>latest</code>.</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