我正在建立一个网站,用户可以关注某些股票,并根据他们关注的股票查看文章
models.py:
from django.db import models
from django.contrib.auth.models import User
class Stock(models.Model):
name = models.CharField(max_length = 50)
ticker = models.CharField(max_length = 50)
def __str__(self):
return self.name
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
followed_stocks = models.ManyToManyField(Stock, blank=True)
def __str__(self):
return self.user.first_name
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()
def __str__(self):
return self.title
views.py:
from django.shortcuts import render
from .models import Article
def index(request):
stocks_user_follows = request.user.profile.followed_stocks.all()
articles_to_display = Article.objects.filter(stock__in=stocks_user_follows) #where the problem lies
return render(request, 'core/index.html', {'stocks_user_follows':stocks_user_follows, 'articles_to_display':articles_to_display})
stocks_user_follows = request.user.profile.followed_stocks.all()
返回正确的值,但是当我在index.html中打印{{articles_to_display}}
时,QuerySet中没有任何内容,这意味着我必须做错事。提前谢谢!