2

I'm trying to create a manager that has a method 'active_or_users' to retrieve all accounts that are active, or that an user has created. An active account has a start date that is either today, or somewhere in the past, and a end date that is somewhere in the future. Right now the active_or_users method works, however it returns duplicates of the same object. It's returning three copies of a user created active job. This is less than ideal.

from django.db.models import Q
from django.db import models
from django.contrib.auth.models import User

class ActiveJobs(models.Manager):
    def active(self):
        return super(ActiveJobs, self).get_query_set().\
            filter(publications__publish_on__lte=date.today(),
                   publications__end_on__gt=date.today())

    def active_or_users(self, user):
        return super(ActiveJobs, self).get_query_set().\
            filter((Q(publications__publish_on__lte=date.today()) &
                    Q(publications__end_on__gt=date.today())) | Q(creator=user))

class Job(models.Model):
    title = models.CharField(max_length=100)
    slug = models.SlugField(blank=True, null=True)
    creator = models.ForeignKey(User)
    objects = ActiveJobs()


class JobPublicationRecord(models.Model):
    job = models.ForeignKey('Job', related_name='publications')
    publish_on = models.DateField(auto_now=False)
    end_on = models.DateField(auto_now=False, auto_now_add=False,
                                blank=True, null=True)
Tomasz Jakub Rup
  • 10,502
  • 7
  • 48
  • 49
user133688
  • 6,864
  • 3
  • 20
  • 36
  • have you tried using the [distinct](https://docs.djangoproject.com/en/1.6/ref/models/querysets/#django.db.models.query.QuerySet.distinct) method? – tutuDajuju Feb 23 '14 at 21:23
  • I have not. And I'm sure that will work. I'm just confused why I'm getting the same object three times? – user133688 Feb 23 '14 at 21:29
  • Since an instance will be returned for every query. I.e: if a Job instance if created by user and another instance of the job if also in the date range specified. – tutuDajuju Feb 23 '14 at 21:31
  • 1
    Ooohhhhhhhhhhhhhhh. Mind Blown. Yes, distinct solved the problem. Thank you guys :D – user133688 Feb 23 '14 at 21:32

1 Answers1

0

To put the comments into an answer

With the OR query, an instance will be returned for every hit of the query. I.e: an instance if a Job is created by user and another instance of the same job if also in the date range specified, etc.

So to fix this, change the method active_or_users to:

def active_or_users(self, user):
    return super(ActiveJobs, self).get_query_set().filter(
        (Q(publications__publish_on__lte=date.today()) &
         Q(publications__end_on__gt=date.today())) | Q(creator=user)).distinct()
tutuDajuju
  • 10,307
  • 6
  • 65
  • 88