Question on returning methods in a class - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: Web Scraping & Web Development (https://python-forum.io/forum-13.html) +--- Thread: Question on returning methods in a class (/thread-24187.html) |
Question on returning methods in a class - menator01 - Feb-03-2020 As the title states, I'm trying to figure out how to access the return on a query in django. models.py class Board(models.Model): category = models.CharField(max_length=20, unique=True) description = models.CharField(max_length=100) def __str__(self): return self.category class Topic(models.Model): subject = models.CharField(max_length=100, unique=True) board = models.ForeignKey(Board, on_delete=models.CASCADE)views.py class HomeView(ListView): model = Board context_object_name = 'categories' template_name = 'boards/forum.html' queryset = Board.objects.all() titles=queryset def get_category_subjects(self): for title in self.titles: subjects = Topic.objects.filter(board_id=title.id) return subjects for category in categories: print(category) for title in category.get_category_subjects: print(title)Any help would be great. Thanks. RE: Question on returning methods in a class - menator01 - Feb-03-2020 Figured it out. Probably not the best approach but works. Revised views.py class HomeView(ListView): model = Board context_object_name = 'categories' template_name = 'boards/forum.html' queryset = Board.objects.all() def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['subjects']=[] for titles in self.queryset: context['subjects'].append(Topic.objects.filter(board_id=titles.id)) return contextIn the html {% for category in categories %} {{category}} {% for titles in subjects %} {% for title in titles %} {% if title.board_id == category.id %} <a href="#">{{title.subject}}</a><br> {% endif %} {% endfor %} {% endfor %} {% endfor %} RE: Question on returning methods in a class - michael1789 - Feb-03-2020 class Board(models.Model): category = models.CharField(max_length=20, unique=True) description = models.CharField(max_length=100) def __str__(self): return self.categoryUsing this as example, if you want to return a self.catagory you'll need to define it with self. above.Then if you want access to it I think this is the way, but instead of using Board use the instance name. what_you_want = Board._str_() RE: Question on returning methods in a class - menator01 - Feb-03-2020 The approach I took works, I just don't really like having to do a loop inside a loop inside a loop. |