通过关系Django获取复杂的对象

时间:2016-07-13 09:03:05

标签: python django django-models

我一直在努力解决Django对象过滤中的以下问题,但没有运气。

为个人提供主键,我想建立一个包含所有里程碑的对象列表。

我的模型布局如下:

        <div class="col-xs-12 col-sm-12 col-md-6 col-lg-3">
            <a href="#" class="button button-primary bpanelbutton">This is a short text</a>
        </div>

        <div class="col-xs-12 col-sm-12 col-md-6 col-lg-3">
            <a href="#" class="button button-primary bpanelbutton">This is a long text like this</a>
        </div>

        <div class="col-xs-12 col-sm-12 col-md-6 col-lg-3">
            <a href="#" class="button button-primary bpanelbutton">This is a long text that is even longer tha the previous button</a>
        </div>

        <div class="col-xs-12 col-sm-12 col-md-6 col-lg-3">
            <a href="#" class="button button-primary bpanelbutton">This is a short text</a>
        </div>
    </div>

</div>

模型如下所示:

TEAM MEMBER -- owns many tasks through --> OWNER -- -- > TASKS -- each task has multiple milestones --> MILESTONES

以下对我不起作用:

class TeamMember(models.Model):
    member_name = models.CharField(max_length=140)
    email = models.EmailField()
    task= models.ManyToManyField(Task, through='Owner')

class Owner(models.Model):
    teammember = models.ForeignKey(TeamMember, on_delete=models.CASCADE) 
    task = models.ForeignKey(Task, on_delete=models.CASCADE)

class Task(models.Model):
    task_name = models.CharField(max_length=140)
    task_description = models.TextField(null=True, blank=True)
    last_updated = models.DateTimeField(null=True, blank=True)

class Milestone(models.Model):
    name = models.CharField(max_length=140)
    task= models.ForeignKey(Task, on_delete=models.CASCADE)
    expected_date = models.DateTimeField()

有什么想法吗?

2 个答案:

答案 0 :(得分:1)

您需要使用多个double.underscore步骤。实际代码取决于您的确切型号和字段名称。 就像是: Milestones.objects.filter(task__owner__teammember__id=1)

答案 1 :(得分:0)

我想获取特定成员的里程碑数据,您可以通过定义值查询集中的字段来获取它,如下所示:

TeamMember.objects.filter(id=1).values
('task__milestone','owner__task__milestone',
'task__milestone__expected_date','task__milestone__name')

我没有测试它,但肯定会得到所有相关信息。