首页 > 解决方案 > Django 从外键获取数据

问题描述

我是一个在新闻网站上工作的新手(或者至少在过去几天里遇到了很多“问题”哈哈)试图尽我所能学习 Django。

这就是我想要做的:

我有一个文章模型,它曾经有 6 个图像字段,我用来发送到模板并渲染图像,每个图像字段都有自己的名称,一切都很好。然后我的任务是将文章图像放在单独的图像模型中。所以我这样做了:

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="image")
    image = models.ImageField("image")
    name = models.CharField(max_length=50, blank=True)

但到目前为止,我无法使用模板访问我的图像

 {{ article.image.url }} or {{ article.image.image.url }}

或任何其他组合。这是为什么 ?我是否正确设置了模型?一个人建议我应该将模型字段从 ForeignKey 更改为 OneToOneField,但我没有得到太多关于为什么和如何的反馈?

那么,我将如何创建一个循环遍历 Articles 模型然后获取每个 Articles 的相关图像的 for 循环?我本质上希望它表现得像我以前一样拥有 6 个不同的字段。(我必须这样做,这是任务的一部分)。

这是我的观点和我用来循环浏览文章并在我的主页上显示 6 条最新消息的“索引”模板。(请忽略标签,我知道它们不是这样工作的......模板只是为了让你明白我在说什么)

我的意见.py:

class IndexView(generic.ListView):

    template_name = 'news/index.html'
    context_object_name = 'latest_article_list'

    def get_queryset(self):
        return Article.objects.all()


class CategoryView(generic.ListView):

    template_name = 'news/categories.html'
    context_object_name = 'category'

    def get_queryset(self):
        return Article.objects.filter(article_category__category_title="Politics")


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")


def article(request, article_id):

    article = get_object_or_404(Article, pk=article_id)
    context = {'article': article,
               'article_category': article.article_category.category_title}

    return render(request, 'news/article.html', context)

我与旧模型一起使用的模板:

        {% for article in latest_article_list %}
        <img class="single-article-img" src="{{ article.image.name.url }}" alt="">

        <div class="container row">
          <!-- Start Left Blog -->
          <div class="article mt-10 col-md-4 col-sm-4 col-xs-12">
            <div class="single-blog" style="margin:10px auto;">
              <div class="single-blog-img">
                <a href="{% url 'news:article' article.id %}#article-title">
                  <img class="for-imgs" src="{{ article.image.url }}" alt="">
                </a>
              </div>
              <div class="blog-meta">

                <span class="date-type">
                  <i class="fa fa-calendar"></i>{{ article.pub_date }}
                </span>
              </div>
              <div class="xx blog-text">
                <h4>
                  <a href="{% url 'news:article' article.id %}#article-title">{{ article.title }}</a>
                </h4>
                <p>
                  {{ article.description|truncatewords:30 }}
                </p>
              </div>
              <span>
                <a href="{% url 'news:article' article.id %}" class="ready-btn">Read more</a>
              </span>
            </div>

          </div>
          {% endfor %}

谢谢 !

标签: pythondjangomodelforeign-keys

解决方案


您需要遍历图像,因为您对单个文章对象有许多图像。您可以使用以下内容在模板中显示图像:

{% if latest_article_list.articleimages %}

   {% for articleimage in latest_article_list.articleimages.all %}

      <img src="{{ articleimage.image.url }}" class="d-block w-100" alt="...">

   {% endfor %}
{% endif %}

推荐阅读