我正在创建一个网站,允许用户关注股票并根据他们关注的内容查看文章。注册后,用户选择他们想要关注的股票。
def follow_stocks_post_registration(request):
all_stocks = Stock.objects.all()
if request.method == 'POST':
stocks_user_selected = request.POST.getlist('stocks_selected')
user_profile = request.user.profile
for stock_name in stocks_user_selected:
stock = Stock.objects.get(name=stock_name)
user_profile.followed_stocks.add(stock)
models.py:
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.username
@receiver(post_save, sender=User)
def update_user_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)
instance.profile.save()
在视图中,stocks_user_selected = request.POST.getlist('stocks_selected')
获取正确的股票列表,但user_profile.followed_stocks.add(stock)
未成功向用户followed_stocks
添加任何股票。我不确定是什么错?
答案 0 :(得分:0)
将对象添加到.save()
后,您需要调用ManyToManyField
方法。此外,您应该在一个查询中过滤stocks
,而不是逐个获取它们。
def follow_stocks_post_registration(request):
all_stocks = Stock.objects.all()
if request.method == 'POST':
stocks_user_selected = request.POST.getlist('stocks_selected')
user_profile = Profile.objects.get(user=request.user)
for stock in Stock.objects.filter(name__in=stocks_user_selected):
user_profile.followed_stocks.add(stock)
user_profile.save()