1

I have this query et:

plist = UserProfile.objects.filter(q).order_by('-created_at')

The model is:

class UserProfile(models.Model):
    user =  models.OneToOneField(User)
    name = models.CharField(max_length=30, blank=True)
    created_at = models.DateTimeField(auto_now_add=True, blank=True)
    #some more fields


    def last_seen(self):
        return cache.get('seen_%s' % self.user.username)


    def online(self):
        if self.last_seen():
            now = datetime.datetime.now()
            if now > self.last_seen() + datetime.timedelta(
                         seconds=settings.USER_ONLINE_TIMEOUT):
                return False
            else:
                return True

What I want to achieve is to filter out further plist to contain only online users.

I tried different tricks, like:

for p in plist:
    if p.online:
        print 'profile onlnine \n', p.id
        online_plist.append(p)
plist = online_plist

But it does not work. So appreciate your hints.

UPDATE: here is how the online users cache is set:

class ActiveUserMiddleware:

    def process_request(self, request):
        current_user = request.user
        if request.user.is_authenticated():
            now = datetime.datetime.now()
            cache.set('seen_%s' % (current_user.username), now, 
                           settings.USER_LASTSEEN_TIMEOUT)
Jand
  • 2,527
  • 12
  • 36
  • 66
  • You need to actually call the `online()` method in your if statement. – Daniel Roseman Oct 01 '17 at 14:01
  • @DanielRoseman not sure how to do that. When I use `if p.online()` instead, I get `User matching query does not exist.`. Will you please elaborate your answer with code sample? – Jand Oct 01 '17 at 14:04
  • 2
    That *is* what you do. That error is presumably caused by something in your `last_seen()` method, which you haven't shown. – Daniel Roseman Oct 01 '17 at 14:06
  • sorry I added `last_seen()` method. The whole online code is from this answer: https://stackoverflow.com/a/32162699/4151875 – Jand Oct 01 '17 at 14:08
  • @DanielRoseman please help! – Jand Oct 01 '17 at 14:18
  • I'm not sure what to you need help with. The error message tells you what is wrong: (at least) one particular UserProfile does not have an associated User. – Daniel Roseman Oct 01 '17 at 14:22
  • Actually I can not get results even for `if not p.online(): ` while there are many offline users. The error track goes down to `return cache.get('seen_%s' % self.user.username) ` – Jand Oct 01 '17 at 14:27
  • I don't understand the relevance of that comment. – Daniel Roseman Oct 01 '17 at 14:36
  • Forget that. It turned out that there were some orphaned profiles so `user.username` did not satisfy. I put the `online` method in try..catch block and problem gone. You are a great tutor DavidRoseman. Could not believe you help people on sundays too. Many thanks! – Jand Oct 01 '17 at 14:51

0 Answers0