嗨,我需要做一个相当复杂的查询。在某种程度上,我可以设法让 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(...) ,这使得表达式不可能。
有任何想法吗?