外键在对象上不可用

时间:2014-05-09 16:48:19

标签: django

非常非常初学的问题令我感到困惑。我在模板中显示外键ArtWorkImages时出现问题,所以我想在视图中调试它,但是ArtworkImage不能在Artwork上使用:

我的模特:

from django.db import models

class Artwork(models.Model):
    title = models.CharField(max_length=200)
    body = models.TextField()
    created_at = models.DateTimeField(auto_now_add=True)

    def __unicode__(self):
        return self.title

class ArtworkImage(models.Model):
    property = models.ForeignKey(Artwork, related_name='images')
    image = models.ImageField(upload_to = "images/")

观点:

from django.shortcuts import render

from erikheide.models import Artwork
from erikheide.models import ArtworkImage

def index(request):
    artworks = Artwork.objects.all()[:5]

    artwork = artworks[0]

    images = artwork.artworkimage_set.all()

    context = {'latest_poll_list': artworks}
    return render(request, 'index.html', context)

错误:

> Traceback (most recent call last):   File
> "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py",
> line 115, in get_response
>     response = callback(request, *callback_args, **callback_kwargs)   File "/home/fhp/Hentede filer/tastypie/django15/erikheide/views.py",
> line 13, in index
>     images = artwork.artworkimage_set.all() AttributeError: 'Artwork' object has no attribute 'artworkimage_set'

无效的模板(没有图像出现)

{% if artworks %}
    <ul>
    {% for artwork in artworks %}
        <li><a href="{{ artwork.title }}/">{{ artwork.body}}</a></li>

        {% for image in artwork.images_set.all %}
        <img src="{{ image.image.url }}">

        {% endfor %}

    {% endfor %}
    </ul>
{% else %}
    <p>No artworks are available.</p>
{% endif %}

2 个答案:

答案 0 :(得分:2)

您已在ForeignKey字段中定义了related_name,您需要使用它来跟踪关系。

替换:

images = artwork.artworkimage_set.all()

使用:

images = artwork.images.all()

另见:What is `related_name` used for in Django?

答案 1 :(得分:0)

尝试

artwork.images.all()

代替

artwork.artworkimage_set.all()

image_set是RelatedManager的默认名称。如果使用外键RelatedManager名称指定related_name重新定义。