1

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

有任何想法吗?

4

1 回答 1

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 示例?

于 2013-04-02T05:54:09.297 回答