Django 1.6获取fk对象

时间:2014-06-29 23:19:36

标签: python django join models mixing

我有这个型号

class Project(models.Model):
    name = models.CharField(max_length=20)
    description = models.CharField(max_length=200, null=True, blank=True)
    creation_date = models.DateTimeField(auto_now_add=True, auto_now=False)
    group_owner = models.ForeignKey(User)

    def __str__(self, y):
        return smart_str(self.name)

class Note(models.Model):
    title = models.CharField(max_length=50, null=True, blank=True)
    content = models.CharField(max_length=1000)
    creation_date = models.DateTimeField(auto_now_add=True, auto_now=False)
    updated_date = models.DateTimeField(auto_now_add=False, auto_now=True)
    projectId = models.ForeignKey(Project, on_delete=models.CASCADE)
    userid = models.ForeignKey(User, on_delete=models.CASCADE)

    def __str__(self):
        return smart_str(self.title)

我想在一个视图中加入它们,当有人进入此网址http://localhost.com:8000/project/ID时会显示该视图。 很明显,ID将取决于Project.id,它必须获取与之相关的所有Notes。

同时我的views.py看起来像这样

class ProjectDetail(generic.DetailView):
    model = Project
    template_name = 'scribere/project/detail.html'

    def get_queryset(self):
        return Project.objects.filter(group_owner__exact=self.request.user.id)

class ProjectNoteList(generic.ListView):
    context_object_name = 'project_note_list'
    template_name = 'scribere/note/index.html'

    def get_queryset(self):
        return Note.objects.filter(userid__exact=self.request.user.id, projectId__exact=self.kwargs['pk'])

和模板

{% extends "base/adminsNavBar.html" %}
{% load i18n %}

{% block head_title %}{% trans 'Projects Details' %}{% endblock %}

{% block breadcrumbs %}
<div class="breadcrumb"><p>{% trans 'Project Details' %}</p></div>
{% endblock %}

{% block content %}
<div class='row'>
    <a href="{% url 'scribere:project_list' %}" class="btn btn btn-primary pull-right" role="button">{% trans 'Back' %}</a>
    <a href="{% url 'scribere:project_note_list' project.id %}" class="btn btn btn-primary pull-right" role="button">{% trans 'Notes' %}</a>
</div>
<div>
{{project.name}}
</div>
<div class = "note-list">
     <ul>
        {% for note in project_note_list %}
            <li>
                <a href= "#"> {{note}} </a>
            </li>
        {% endfor %}
    </ul>
</div>
{% endblock %}

不会加载有关该笔记的任何信息。我错过了什么?

1 个答案:

答案 0 :(得分:0)

除非您使用某些信息填充project_note_list,否则将无需迭代。

凭借ForeignKey s,并且Many to one relation project对象将有一组与之关联的注释,而无需查找它们。

您应该可以使用project.note_set.all()或在模板中使用以下方式查询它们:

{% for note in project.note_set %}