这是我的模型结构。
Institution
- name
- logo
- ....
Course
- Owner ( foriegnKey with Institution )
- name
- terms
- .....
现在,我调用data's。
courses = Course.objects.filter(name__icontains=query).values('id','name','terms','owner__name', 'owner__logo')
并试图将owner__logo显示为{{data.owner__logo.url}}
。但它不起作用,正如img src所显示的(未知)。但是当这个机构的标志在其他视图上工作时,当我直接调用它时。但是当我通过关系呼叫时,它不起作用。
如果我使用{{data.owner__logo}}
,那么它只传递url而不传递完整路径。如何使这个工作,请帮助!
我尝试过的一个方法是…
# Use the FK object id (owner_id) since you're dealing with a FK.
courses = Course.objects.filter(name__icontains=query).values('id','name','terms','owner_id')
如果您应该打印courses dictionary
,您将看到它包含的fields
为每门课程。在本例中,您将看到FK
与object
对应的id
。例子:
{'id': 10, 'owner_id': 7, 'name': 'Random', 'terms': 'Anything', ...}
我从这里做了什么,因为courses
object
是dictionary
,我添加了一个新的key
,value
是url
的标志。
for course in courses:
# First is to get the owner object with the course['owner_id']
owner = Institution.objects.get(id=course['owner_id'])
# From the owner object, you have access to the logo and it's URL
# Creating a new key called 'logo_url' and assigning the owner logo URL to it
course['logo_url'] = owner.logo.url
# Add the courses dictionary to the context variable
context['courses'] = courses
然后在您的模板中,您可以访问每个course
的logo_url
。
{% for course in courses %}
<img src="{{ course.logo_url }}"/>
{% endfor %}
选项#2:更有效的方法
这里的下一个选项是使用template filter
来获得Institution object
的标志url
,而你循环遍历模板中的项目。
在你的custom_tags.py
文件中:
from django import template
from django.shortcuts import get_object_or_404
register = template.Library()
@register.filter
def get_logo_url(bypass, owner_id):
# owner = Institution.objects.get(id=owner_id)
# or
owner = get_object_or_404(Institution, id=owner_id) # Recommended
if owner:
url = owner.logo.url
else:
url = ""
return url
在你的template
和for loop
.
{% load custom_tags %} # Must do to be able to use the custom filter
{% for course in courses %}
{% with logo_url=""|get_logo_url:course.owner_id %}
<img src="{{ logo_url }}" />
{% endwith %}
{% endfor %}
如果您不熟悉django
自定义tags
和filters
,您可以在这里查看文档。