查询一定数量的对象django

时间:2018-04-26 20:32:06

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

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

如何实现这一目标?

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

1 个答案:

答案 0 :(得分:2)

我无法确定哪些条件可以确定哪些文章是“最后一个”或“第一个”,但您只需要更改代码的一行:

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

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

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