【发布时间】:2016-01-01 10:31:00
【问题描述】:
我有一个这样的模型
class Job(models.Model):
description = models.CharField(max_length=255)
user = models.ForeignKey(User)
date = models.DateField()
slot = models.CharField(max_length=10, choices=SLOT_CHOICES)
location = models.ForeignKey(Location)
objects = JobManager()
searches = geomodels.GeoManager()
class Meta:
verbose_name_plural = "Job"
unique_together = ('date', 'slot', 'user')
def __str__(self):
return "{0}-{1}".format(self.user.first_name, self.date)
class Applied(models.Model):
user = models.ForeignKey(User)
job = models.ForeignKey(Job, null=True, blank=True)
action_taken = models.BooleanField(default=False)
is_declined = models.BooleanField(default=False)
class Meta:
verbose_name_plural = "Job Applications"
unique_together = ('user', 'job', )
我想搜索某个日期范围内的所有工作,并显示用户是否可以申请、已申请或已被拒绝。应用信息在应用模型中。
jobs = Job.searches.filter(**kwargs)\
.filter(date__range=(date_from, date_to),
visibility=VisibilityStatus.PUBLIC,
status=JobStatus.AVAILABLE)\
.prefetch_related('applied_set')\
.select_related('user__surgeryprofile__location')\
.order_by('date')
但我无法让它工作,它没有对数据库中的应用表进行左连接。任何如何让它工作的建议。
谢谢
【问题讨论】:
-
请原谅我的提问,但内部连接不够吗?
-
内连接只会带来两个表中存在的行,我想要一个左连接,因为如果用户已经应用,我想要日期范围和应用表中的行之间的作业表的所有行对于那个工作,如果它被拒绝了。
-
即使没有连接,您的代码也应该为您提供正确的结果(带有可能为空的应用集的过滤作业)。 “在大多数情况下,prefetch_related 将使用使用‘IN’运算符的 SQL 查询来实现。” docs.djangoproject.com/en/1.7/ref/models/querysets/…
-
虽然不工作,正在生成的查询甚至没有对应用表的任何引用。
标签: django django-queryset django-1.7