【发布时间】:2013-03-22 19:56:01
【问题描述】:
您好,我需要做一个相当复杂的查询。而且我可以在一定程度上设法让 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(...),这使得表达式不可能。
有什么想法吗?
【问题讨论】:
-
如果您尝试的第一个查询不是
patent_owner__company而不是projectidea__company吗? -
不确定这是否“业务”正确。但只有在公司开始第一个项目后,想法才会获得专利。
标签: django join filter many-to-many