【问题标题】:Query a certain number of objects django查询一定数量的对象django
【发布时间】:2018-04-26 20:32:05
【问题描述】:

我正在创建一个网站,允许用户关注某些股票并查看与他们关注的内容相关的文章。在“index.html”中,我只想为用户关注的每个 Stock 显示最后 5 个 Articles。

如何做到这一点?

models.py:

class Stock(models.Model):
        name = models.CharField(max_length = 50)
        ticker = models.CharField(max_length = 50)

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    followed_stocks = models.ManyToManyField(Stock, blank=True)

    @receiver(post_save, sender=User)
    def update_user_profile(sender, instance, created, **kwargs):
        if created:
            Profile.objects.create(user=instance)
        instance.profile.save()

class Article(models.Model):
    stock = models.ForeignKey(Stock, on_delete=models.CASCADE, default = 0 )
    title = models.CharField(max_length = 200)
    url = models.URLField()
    description = models.TextField()

views.py:

def index(request):
    stocks_user_follows = list(request.user.profile.followed_stocks.all())
    articles_to_display = Article.objects.filter(stock__in = stocks_user_follows)

    return render(request, 'core/index.html', {'stocks_user_follows':stocks_user_follows, 'articles_to_display':articles_to_display})

index.html:

<div class="container">
    <div class="row">
        {% for stock in stocks_user_follows %}
            <div class="col-md-4">
                <div class="card">
                    <h2>{{ stock }}</h2>
                    <ul>
                        {% for article in articles_to_display %}
                            {% if article.stock == stock %}
                                <li><a  href="{{article.url}}">{{ article.title }}</a></li>
                            {% endif %}
                        {% endfor %}
                    </ul>
                    <a href="#" class="btn btn-light w-50 mx-auto mb-4">All {{ stock }} News</a>

                </div>
            </div>

forms.py:

class StockFollowForm(forms.Form):
    stocks = forms.ModelMultipleChoiceField(required =False,
                                           widget=forms.CheckboxSelectMultiple,
                                           queryset=Stock.objects.all(),
                                           label= "",
                                           )

【问题讨论】:

  • 停止发布重复的问题。

标签: django django-models django-forms django-templates django-views


【解决方案1】:

我无法确定您将根据哪些标准来终止哪些文章是“最后一个”或“第一个”,但您只需更改一行代码:

def index(request):
    ...
    articles_to_display = Article.objects.filter(stock__in = stocks_user_follows)[:5]
    ...

Slice the quesrysets 将其限制为最多 5 个实例。

但是您应该考虑向查询集添加order_by 调用,以便获得一致的结果(每次相同的 5 个元素)。您只需定义要按哪个字段对数据进行排序。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-08-19
    • 2018-03-22
    • 2021-08-04
    • 1970-01-01
    • 2011-02-19
    • 1970-01-01
    • 2021-03-24
    • 2014-08-11
    相关资源
    最近更新 更多