首页 > 解决方案 > Django 在模板中显示外键引用

问题描述

我正在尝试在 django 中开发应用程序。我有一个可能链接到模型Publication也可能不链接到Project模型的通用表。

这是一些代码:

项目

class Project(models.Model):
    title = models.CharField(max_length=254)
    abstract = models.CharField(max_length=254)
    link = models.URLField()

    def __str__(self):
        return self.title

出版物

class Publication(models.Model):
    id = models.IntegerField(primary_key=True)
    title = models.CharField(max_length=254)
    authors_string = models.CharField(max_length=254, default='')
    project = models.ForeignKey(Project, on_delete=models.DO_NOTHING, blank=True, null=True)

    def __str__(self):
        return self.title

现在的问题是我试图在模板中显示这个引用。我怎样才能做到这一点?publication.project.title 似乎不起作用。一般出版物似乎没有项目领域

模板

{% for p in projects %}
    <option value="">{{ p.title }}</option>
    {% if p.projects.id %}
        <option>{{ p.title }}</option>
    {% endif %}
{% endfor %}

我错过了什么?

编辑

@login_required
def profile(request, initial_page=1):

    # Get query params
    offset = (initial_page-1) * 10
    limit = offset + 10

    # Handle default GET request
    current_user = request.user
    pending_publications = Publication.objects.filter(authors=current_user).order_by('-year')
    number_of_pending_publications = Publication.objects.filter(authors=current_user).count()
    number_of_pending_pages = int(number_of_pending_publications/10) + 1
    confirmed_publications = Publication.objects.filter(authors2=current_user).order_by('-year')
    number_of_confirmed_publications = Publication.objects.filter(authors2=current_user).count()
    number_of_confirmed_pages = int(number_of_confirmed_publications/10) + 1
    projects = Project.objects.all()

    if (number_of_confirmed_publications % 10) == 0:
        number_of_confirmed_pages -=1 
    if (number_of_pending_publications % 10) == 0:
        number_of_pending_pages -=1

    # Set up form defaults
    default_form_values = {
        "first_name" : request.user.first_name, 
        "last_name" : request.user.last_name,
        "email" : request.user.email, 
        "organization" : request.user.organization,
        "bio" : request.user.bio,
    }

    # Set up context variables for html
    context = {
        'form': UpdateProfileForm(initial = default_form_values),
        'projects' : projects,
        'confirmed_publications' : confirmed_publications[offset:limit],
        'number_of_confirmed_publications' : number_of_confirmed_publications,
        'number_of_confirmed_pages' : number_of_confirmed_pages,
        'pending_publications' : pending_publications[offset:limit],
        'number_of_pending_publications' : number_of_pending_publications,
        'number_of_pending_pages' : number_of_pending_pages,
        'initial_pending_page' : initial_page,
        'initial_confirmed_page' : 1,

    }

    # Render page
    return render(request, 'main/publication.html', context)

标签: djangodjango-modelsjinja2

解决方案


您正在处理 1 -> n 关系。为了PublicationProject实例访问实例的属性,您需要调用yourmodel_set或提供相关名称。

1.使用_set

假设您Project的视图中有一个实例,并且想要遍历所有相关的出版物,这将是例如

for pub in project.publication_set.all():
    print(pub.title)

在使用 django 模板语言的模板中,这将是(使用您的模板):

{% for p in projects %}
{{ p.title }}
    {% for pub in p.publication_set.all %}
    {{ pub.title }}
    {% endfor %}
{% endfor %}

2.使用相关名称

如果您不喜欢 _set 东西,您可以添加相关名称并使用它来访问相关对象。

在您的模型中:

class Publication(models.Model):
    id = models.IntegerField(primary_key=True)
    title = models.CharField(max_length=254)
    authors_string = models.CharField(max_length=254, default='')
    project = models.ForeignKey(Project, on_delete=models.DO_NOTHING, blank=True, null=True, related_name='publications')

    def __str__(self):
        return self.title

然后在你的模板中

{% for p in projects %}
    {{ p.title }}
        {% for pub in p.publications.all %}
        {{ pub.title }}
        {% endfor %}
{% endfor %}

如果您想从 a 访问项目Publication,则您所说的语法是正确的,例如:

pub.project.title

推荐阅读