Django:显示“精选”项目?

时间:2018-05-13 02:16:03

标签: python django python-3.x django-models django-templates

我对整理一些物品有一点难题。我有一个名为features的字段,它是一个布尔值。我试图首先显示特色硬币,然后剩余的将按不同的指标排序。在此代码中我使用pub_date。

但是,当我在我的模板中为特色项目添加if语句时,它仍然显示那些设置为false的那些。我将在下面发布代码。

index.html循环和if

    {% if featured_coins_list %}
            {% for coin in featured_coins_list %}
            <div class="large-6 medium-6 cell">
                <h2><a href="/coins/{{ coin.id }}/">{{ coin.name }}</a></h2>
                <p>Ticker: {{ coin.ticker }}</p>
                <p>{{ coin.summary }}</p>
                <a href="/coins/{{ coin.id }}" class="button">More Info</a></strong>
            </div>
        {% endfor %}
        {% endif %}

        {% if latest_coins_list %}
          {% for coin in latest_coins_list %}
            <div class="large-6 medium-6 cell">
              <h2><a href="/coins/{{ coin.id }}/">{{ coin.name }}</a></h2>
              <p>Ticker: {{ coin.ticker }}</p>
              <p>{{ coin.summary }}</p>
              <a href="/coins/{{ coin.id }}" class="button">More Info</a></strong>
            </div>
            {% endfor %}
          </div>
{% else %}
    <p>No coins are available.</p>
{% endif %}

views.py索引

def index(request):
    featured_coins_list = Coin.objects.order_by('-featured')[:4]
    latest_coins_list = Coin.objects.order_by('-pub_date')[:8]
    context = {'featured_coins_list': featured_coins_list,
               'latest_coins_list': latest_coins_list}
    return render(request, 'coins/index.html', context)

models.py

class Coin(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=100)
    ticker = models.CharField(max_length=5)
    featured = models.BooleanField(default=False)
    logo = models.ImageField(upload_to='uploads/', verbose_name='image')
    website = models.URLField(max_length=200, default="https://example.com/")
    reddit = models.URLField(max_length=200, default="https://reddit.com/r/")
    twitter = models.URLField(max_length=200, default="https://twitter.com/")
    summary = models.CharField(max_length=500, blank=True)
    description = models.TextField()
    pub_date = models.DateTimeField('date published')

    def __str__(self):
        return self.ticker

    def is_featured(self):
        return self.featured

    def was_published_recently(self):
        return self.pub_date >= timezone.now() - datetime.timedelta(days=1)

我应该如何列出首先设置为真的特色硬币然后显示剩余的项目?

1 个答案:

答案 0 :(得分:2)

您需要在查询集中过滤featured=True

def index(request):
    featured_coins_list = Coin.objects.filter(featured=True).order_by('-featured')[:4]
    latest_coins_list = Coin.objects.order_by('-pub_date')[:8]
    context = {'featured_coins_list': featured_coins_list,
               'latest_coins_list': latest_coins_list}
    return render(request, 'coins/index.html', context)