Barburka
Barburka

Reputation: 465

Django filter queryset in reverse relation

Code I'm working with:

class Message(models.Model):
    from_who = models.ForeignKey(User, related_name='sent')
    to = models.ForeignKey(User, related_name='recieved')
    text = models.CharField(max_length=1000)
    timestamp = models.DateTimeField(auto_now_add=True)
    new = models.BooleanField(default=True)

Can I display in template User.recieved messages only with new = True when I'm using request.user not context? If yes, how?

Upvotes: 0

Views: 659

Answers (2)

Barburka
Barburka

Reputation: 465

For someone who is looking an answer:

#models.py
class Message(models.Model):
from_who = models.ForeignKey(User, related_name='sent')
to = models.ForeignKey(User, related_name='recieved')
text = models.CharField(max_length=1000)
timestamp = models.DateTimeField(auto_now_add=True)
new = models.BooleanField(default=True)

new_messages = NewMessageManager()

#managers.py
class NewMessageManager(models.Manager):

def new_messages(self):
    return super(NewMessageManager, self).get_queryset().filter(new=True)

#template.html
{% if request.user.recieved.new_messages %}
  <span class="badge badge-danger">{{ request.user.recieved.new_messages.count }}</span>
{% endif %}

Upvotes: 0

brandondavid
brandondavid

Reputation: 200

If I understand the question - you want to show all new message to the logged in user without adding any additional context to the view? Try this (and note that I changed the spelling of "received":

{% for message in request.user.received.all %}

    {% if message.new %}
        {{ message }}<br />
    {% endif %}

{% endfor %}

Upvotes: 1

Related Questions