如何在视图中将一个模型对象映射到另一个模型对象

时间:2015-05-26 01:10:35

标签: django django-views

我有一堆消息记录,我想分配给不同的任务箱。

#models.py

class TaskBox(models.Model):
    name = models.CharField(max_length=64, blank=False)

    def __str__(self):
        return u'%s' % (self.name)

    class Admin:
        pass

class InboxEntry(models.Model):
    job_number = models.CharField(max_length=14, unique=False, blank=False, null=False)
    job_name = models.CharField(max_length=64, unique=False, blank=False, null=False)
    request = models.CharField(max_length=64, choices=PRINT_CHOICES, blank=True, null=True)
    date_due = models.DateTimeField(("Due"),auto_now=False)
    note = models.TextField(max_length=1000, unique=False, blank=True, null=True)
    assigned_by = models.ForeignKey(UserProfile, blank=False, null=False)
    box = models.ForeignKey(TaskBox)
    assigned_to = models.ManyToManyField(UserProfile, related_name='name', blank=True)
    status = models.CharField(max_length=30, choices=STATUS_CHOICES, default="Awaiting Action")

    def __str__(self):
        return u'%s %s' % (self.job_number, self.job_name)

    class Admin: 
        pass

    class Meta:
        ordering = ['status']

这个想法是让模板有一些通用标签,比如{{for taskboxes}}},为每个任务箱创建一个单独的div,它将为该框的记录保存一个表。我的问题是构建视图函数......

#views.py

def display_prdInboxEntry(request, id):
    if request.method == 'POST':
        form = PrdInboxForm(request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('taskmanager/display/'+ id +'/')
        else:
            form = PrdInboxForm(request.POST)
            return HttpResponseRedirect('taskmanager/display/'+ id +'/')

    else:
        form = PrdInboxForm()
        user = request.user
        **taskboxes = TaskBox.objects.all()
        records_1 = InboxEntry.objects.filter(taskboxes[id]=1)
        records_2 = InboxEntry.objects.filter(taskboxes[id]=2)
        records_3 = InboxEntry.objects.filter(taskboxes[id]=3)
        ..... **

        return render_to_response('taskmanager/taskmanager_view.html', {'form': form, 'taskboxes': taskboxes, 'records_1' : records_1, 'records_2' : records_2, 'records_3' : records_3, 'user': user}, context_instance=RequestContext(request))

InboxEntry模型有一个名为" box"的字段。这只是对TaskBox模型的引用。我需要一种方法来映射说...任务框id 1与所有的InboxEntry对象" box = 1"这样我就可以适当地填充模板。我可以构建适应这个的功能,还是我完全以错误的方式去做?

1 个答案:

答案 0 :(得分:0)

听起来你正在寻找反向查找的自动生成属性。您可以获得与QuerySet相关联的所有InboxEntries TaskBox,如下所示:

TaskBox.objects.filter(id=1).inboxentry_set.all()

请参阅documentation on related objects