在Django中通过表格过滤

时间:2016-07-13 10:16:24

标签: django django-models

Django是否支持对直通表进行过滤?到目前为止,我还没有运气。

我有以下三种模式:

class TeamMember(models.Model):
    member_name = models.CharField(max_length=140)
    title = models.CharField(max_length=140, null=True, blank=True)
    email = models.EmailField()

class Report(models.Model):
    report_name = models.CharField(max_length=140)
    report_description = models.TextField(null=True, blank=True)

class Owner(models.Model):
    teammember = models.ForeignKey(TeamMember, on_delete=models.CASCADE) 
    report = models.ForeignKey(Report, on_delete=models.CASCADE)
    primary_owner = models.IntegerField()

并希望根据主要所有者标记(1或0)进行过滤,以获取该报告的主要所有者。

我试过了:

owners = TeamMember.objects.filter(report__id=id,primary_owner__contains=1).distinct()[:1]

虽然这不起作用。

2 个答案:

答案 0 :(得分:1)

您的起点是TeamMemberteammemberOwner具有反向关系,您需要使用该关系来过滤Owner.reportOwner.primary_owner位。

e.g。

owners = TeamMember.objects.filter(
    owner__report_id=id, #its also possible to use: owner__report__id
    owner__primary_owner=1 #I have no idea why you use contains on an IntegerField?
).distinct()[:1]

答案 1 :(得分:0)

这应该有效:

primary_owner = TeamMember.objects.filter(owner__report__id=id,
                                          owner__primary_owner=1).first()

模型名称Owner有点误导,ReportOwnership(或建议任何其他!)。此外,primary_owner应为BooleanField