外键在对象上不可用
Posted
技术标签:
【中文标题】外键在对象上不可用【英文标题】:Foreign key not available on object 【发布时间】:2014-06-27 12:15:57 【问题描述】:让我困惑的非常初级的问题。我在模板中显示外键 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 %
【问题讨论】:
【参考方案1】:您已经在ForeignKey
字段上定义了related_name
,您需要使用它来遵循关系。
替换:
images = artwork.artworkimage_set.all()
与:
images = artwork.images.all()
另见:What is `related_name` used for in Django?
【讨论】:
谢谢,它工作得很好。我想我一定找到了一些旧文档,因为我使用了 _set 语法。【参考方案2】:试试
artwork.images.all()
改为
artwork.artworkimage_set.all()
image_set
是 RelatedManager 的默认名称。如果related_name
用外键指定RelatedManager名称重新定义。
【讨论】:
以上是关于外键在对象上不可用的主要内容,如果未能解决你的问题,请参考以下文章
EKEventStore:“initWithAccessToEntityTypes”不可用:在 iOS 上不可用
UIUserInterfaceStyle 键在 Xcode 12 的 Info.plist 中不可用,如何从 Info.plist 禁用 Xcode 12 中的暗模式?
为啥 AUNetSend 在 iOS 上不可用? (或任何替代建议)
pod 更新后编译时出现错误“'sharedApplication' 不可用:在 iOS (App Extension) 上不可用....”