我有以下两种型号:
class Job(models.Model):
title = models.CharField(_('title'), max_length=50)
description = models.TextField(_('description'))
category = models.ForeignKey(JobCategory, related_name='jobs')
created_date = models.DateTimeField(auto_now_add=True)
class JobCategory(models.Model):
title = models.CharField(_('title'), max_length=50)
slug = models.SlugField(_('slug'))
到目前为止,这是我查询的地方:
def job_categories():
categories = JobCategory.objects.annotate(num_postings=Count('jobs'))
return {'categories': categories}
问题在于我只想计算过去30天内创建的作业。我想返回所有类别,而不仅仅是那些有合格工作的类别。
答案 0 :(得分:4)
只是一个猜测...但这会有效吗?
def job_categories():
thritydaysago = datetime.datetime.now() - datetime.timedelta(days=30)
categories = JobCategory.objects.filter(job__created_date__gte=thritydaysago).annotate(num_postings=Count('jobs'))
return {'categories': categories}
有关跨越查询的详细信息,请参阅“lookups-that-span-relationships”。 嗯...可能需要另外一个查询来获取所有类别...
答案 1 :(得分:1)
我决定采用不同的方式,并选择不使用注释。我在Job模型中添加了一个管理器,它只返回活动(30天或更短时间)的作业,并在JobCategory模型上创建了一个属性,用于查询实例的作业计数。我的templatetag只返回了所有类别。这是相关的代码。
class JobCategory(models.Model):
title = models.CharField(_('title'), max_length=50, help_text=_("Max 50 chars. Required."))
slug = models.SlugField(_('slug'), help_text=_("Only letters, numbers, or hyphens. Required."))
class Meta:
verbose_name = _('job category')
verbose_name_plural = _('job categories')
def __unicode__(self):
return self.title
def get_absolute_url(self):
return reverse('djobs_category_jobs', args=[self.slug])
@property
def active_job_count(self):
return len(Job.active.filter(category=self))
class ActiveJobManager(models.Manager):
def get_query_set(self):
return super(ActiveJobManager, self).get_query_set().filter(created_date__gte=datetime.datetime.now() - datetime.timedelta(days=30))
class Job(models.Model):
title = models.CharField(_('title'), max_length=50, help_text=_("Max 50 chars. Required."))
description = models.TextField(_('description'), help_text=_("Required."))
category = models.ForeignKey(JobCategory, related_name='jobs')
employment_type = models.CharField(_('employment type'), max_length=5, choices=EMPLOYMENT_TYPE_CHOICES, help_text=_("Required."))
employment_level = models.CharField(_('employment level'), max_length=5, choices=EMPLOYMENT_LEVEL_CHOICES, help_text=_("Required."))
employer = models.ForeignKey(Employer)
location = models.ForeignKey(Location)
contact = models.ForeignKey(Contact)
allow_applications = models.BooleanField(_('allow applications'))
created_date = models.DateTimeField(auto_now_add=True)
objects = models.Manager()
active = ActiveJobManager()
class Meta:
verbose_name = _('job')
verbose_name_plural = _('jobs')
def __unicode__(self):
return '%s at %s' % (self.title, self.employer.name)
和标签......
def job_categories():
categories = JobCategory.objects.all()
return {'categories': categories}