django - Django - 从外键字段访问图像
问题描述
我试图制作一个单独的图像模型来保存我所有的图片模型。我已经使用我的文章模型的外键创建了图像模型。
这样做之后,我被卡住了,我试图让每篇文章的图片为相关文章渲染,但我没有取得任何进展。有人有空来帮忙吗?
谢谢 !!!
我的观点:
class ArticlesView(generic.ListView):
context_object_name = 'latest_article_list'
template_name = 'news/articles.html'
paginate_by = 5
def get_context_data(self, **kwargs):
context = super(ArticlesView, self).get_context_data(**kwargs)
context['categories'] = Category.objects.all()
return context
def get_queryset(self):
category_pk = self.request.GET.get('pk', None)
if category_pk:
return Article.objects.filter(article_category__pk=category_pk).order_by("-pub_date")
return Article.objects.order_by("-pub_date")
我的模型:
class Article(models.Model):
title = models.CharField('title', max_length=200, blank=True)
slug = AutoSlugField(populate_from='title', default="",
always_update=True, unique=True)
author = models.CharField('Author', max_length=200, default="")
description = models.TextField('Description', default="")
is_published = models.BooleanField(default=False)
article_text = models.TextField('Article text', default="")
pub_date = models.DateTimeField(default=datetime.now, blank=True)
article_category = models.ForeignKey(Category, on_delete="models.CASCADE", default="")
def __str__(self):
return self.title
class ArticleImages(models.Model):
article = models.ForeignKey(Article, on_delete="models.CASCADE", related_name="Images")
image = models.ImageField("Image")
谢谢堆栈!!
解决方案
您已将 ArticleImage 定义related_name
为“图像”,但您尝试通过article.article_image
模板访问该关系。访问文章图像的正确方法是通过article.Images.image
但是,由于您将图像的关系指定为ForeignKey,所以一个ArticleImage 只能有一个Article,而一个Article 可以有多个图像。(所谓的多对一关系)。您应该将 ArticleImage 中的 ForeignKey 更改为OneToOneField
. 但是,既然 ArticleImage 是与 Article 的 OneToOne 关系,为什么不image
直接在文章上设置一个字段呢?
此外,您不应将 related_name 大写'Images'
,如果它是一对一字段,请考虑将其更改为单数'image'
。
推荐阅读
- javascript - MSE WebM 在没有结束事件的持续时间之前完成
- amazon-kms - Aws KMS 客户端 PublicKeyResponse,如何使用 Java 客户端获取 PublicKey
- azure-devops - Azure 管道将 pom 存储库协议从 https 更改为 http
- azure - 如何使用 Visio 为 Kusto 绘制应用程序架构图?
- c++ - 在没有 system() 的父窗口中运行外部程序
- html - 有人可以告诉我为什么我的悬停和焦点不起作用
- mysql - MySQL - 计算多列的行
- c++ - 库包括 WinRT Broken
- javascript - 如何以我从 redux 获得的状态保存数据,然后直接渲染而不是使用 .map() 函数?
- javascript - 无法显示图像无序列表中的下一个和上一个所有图像