首页 > 解决方案 > 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")

谢谢堆栈!!

标签: djangodjango-modelsmodel

解决方案


您已将 ArticleImage 定义related_name为“图像”,但您尝试通过article.article_image模板访问该关系。访问文章图像的正确方法是通过article.Images.image

但是,由于您将图像的关系指定为ForeignKey,所以一个ArticleImage 只能有一个Article,而一个Article 可以有多个图像。(所谓的多对一关系)。您应该将 ArticleImage 中的 ForeignKey 更改为OneToOneField. 但是,既然 ArticleImage 是与 Article 的 OneToOne 关系,为什么不image直接在文章上设置一个字段呢?

此外,您不应将 related_name 大写'Images',如果它是一对一字段,请考虑将其更改为单数'image'


推荐阅读