让django使用内连接

时间:2013-04-01 17:48:12

标签: django join filter many-to-many

嗨,我需要做一个相当复杂的查询。在某种程度上,我可以管理django返回对象,但有些是重复的。

模型如下:ProjectType,ProjectIdea。我需要从公司可以启动的数据库中选择项目类型。每家公司都可以启动他们有想法的项目,而不是专利项目。如果他们的专利已过期,即使他们没有这个想法,他们也可以启动它。

class ProjectType(models.Model):
    patent_expires = models.DateTimeField(null=True)
    patent_owner = models.ForeignKey(Company,null=True)

#This really is just MtoN relationship
class ProjectIdea(models.Model):
    project = models.ForeignKey(ProjectType)
    company = models.ForeignKey(Company)

我尝试了以下查询:

#problem is that ProjectType(s), where patent expired and the company has idea for is returned twice
models.ProjectType.objects.filter(Q(projectidea__company=request.user.company) | Q(patent_expires__lt=timezone.now()))

#doesn't return projects where patent is expired and idea exists
models.ProjectType.objects.filter(Q(projectidea__company=request.user.company),(Q(patent_owner__isnull=True) | Q(patent_owner=request.user.company))).filter(Q(patent_expires__lt=timezone.now()) | Q(patent_owner__isnull=True))

#returns only the projects where patent expired and idea exists. Omits the not patented projects, where idea exists
q = models.ProjectType.objects.filter(Q(patent_expires__lt=timezone.now()) | Q(patent_owner=request.user.company)).filter(projectidea__company=request.user.company,patent_owner__isnull=True)

.distinct() #has no effect what so ever

我尝试了多种变体,但我无法弄清楚如何正确编写它。我也尝试过只使用.exclude(),但似乎我不能使用Q(...)& Q(...)在其中,使表达不可能。

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

天真地我会认为这是有效的,(假设我已经正确地捕捉了你的意图)。

our_ideas = Q(projectidea__company=request.user.company)
has_patent = Q(patent_owner__isnull=False)
patent_expired = Q(patent_expires__lt=timezone.now())

startable_projects = models.ProjectType.objects\
    .filter( (~has_patent & our_ideas) | (has_patent & patent_expired) ).distinct()

如果没有,是否可以提供生成的SQL,以及您希望看到的SQL示例?