David542
David542

Reputation: 110562

How to get the current user for a model field

For the following unread definition, how would I get the current user to be able to count the number of MessageThreads a given user has?

class MessageThread(models.Model):
    subject = models.CharField(max_length=256, blank=False)

    def unread(self):
        return self.objects.filter(***messagerecipient__recipient='current user'***).distinct().count()

class MessageRecipient(models.Model):
    message = models.ForeignKey(Message)
    recipient = models.ForeignKey(User)
    status = models.CharField(max_length=20, choices=MESSAGE_STATUS, default="unread")

Upvotes: 0

Views: 635

Answers (1)

Timmy O'Mahony
Timmy O'Mahony

Reputation: 53998

You have to pass the request to the method:

def unread(self, request):
    return self.objects.filter(messagerecipient__recipient=request.user).distinct().count()

but this doesn't make sense as you are calling a model method (which operates on a particular rows, i.e. a single MessageThread) - you should write a model manager to operate on the entire table (i.e. find all unread threads in the table MessageThread)

class MessageThreadManager(models.Manager):
    def get_unread_threads(self, user):
        return self.objects.filter(messagerecipient__recipient=user).distinct()

class MessageThread(models.Model):
    objects = MessageThreadManager()

so now you can call:

unread_threads = MessageThread.objects.get_unread_threads(some_user_obj)

Upvotes: 1

Related Questions