Phil H Phil H - 4 months ago 64
Python Question

AttributeError: 'QuerySet' object has no attribute 'related_stocks'

Django newbie here. I'm trying to create a simple app to discuss stocks, where users can create topics and establish many-to-many relationship to specific stocks. In the topic-detail page, I would like to show all the stocks related to that topic. I'm running into a roadblock: AttributeError 'QuerySet' object has no attribute 'related_stocks'. Despite going through similar questions others have asked, I still can't seem to figure it out. Any help would be greatly appreciated. Please see my code below:

models.py

class Topic(models.Model):
title = models.CharField(max_length=50)
related_stocks = models.ManyToManyField(Stock)
slug = models.SlugField(max_length=200, blank=True)
created = models.DateField(auto_now_add=True,
db_index=True)
def __str__(self):
return self.title

def save(self, *args, **kwargs):
if not self.slug:
self.slug = slugify(self.title)
super(Topic, self).save(*args, **kwargs)

def get_absolute_url(self):
return reverse('comments:topic_detail', args=[self.id, self.slug])


views.py

def topic_detail(request, id, slug):
topic = Topic.objects.all().filter(id=id, slug=slug)
related_stocks = topic.related_stocks
return render(request,
'comments/comment/topic-detail.html',
{'section': 'topics',
'topic': topic,
'related_stocks': related_stocks})


topic-detail.html

{% extends "base.html" %}

{% block title %}{{ topic.title }}{% endblock %}

{% block content %}
<h1>Stocks associated with {{ topic.title }}.</h1>
{% for related_stock in related_stocks %}
<ul>
<a href="{{ related_stock.get_absolute_url }}">
{{ related_stock.ticker }}
</a>
</ul>
{% endfor %}
{% endblock %}

Answer

You should user get instead of filter:

topic = Topic.objects.get(id=id, slug=slug)

filter returns array. get returns only one object and you need to handle object does not exist scenario.

Comments