I'm having trouble passing data from a Django model to a a Django template. The code below works, but I'm it seems clunky and I'm a bit confused by why it works. I'm trying to read a random entry from my database for each one of my models. I then want to print the data from each model on my home template. I thought I could add each model to a single dictionary, then iterate through the dictionary of dictionaries in my template, but that didn't work ( I know the models have different fields, but I was planning on working around that later). I played around with it for a while, and realized that my for loops weren't actually iterating through the dictionary of dictionaries, but was actually just reading each individual entry in the dictionary through its key. Additionally, it doesn't seem like the for loops are doing any iterating, since I can access the fields of my model directly with the .field notation. This seems to be the only method that works but I'm still not entirely sure why. Could anyone clarify why this works, or let me know if there is a more straightforward way of reading the dictionary? Here is the function that renders the template:
def home(request):
# Get a random song and album from the database
randomSong = randint(1,501)
randomAlbum = randint(1,501)
songChoice = Songs.objects.filter(rank = randomSong).values()
albumChoice = Albums.objects.filter(rank = randomAlbum).values()
entry = {'ent': songChoice, 'entry': albumChoice}
return render(request,'rollingStone/home.html', entry)
And this is the template that home renders:
{% extends "rollingStone/layout.html" %}
{% block title %}
A Record A Day
{% endblock %}
{% block body %}
{% for song in ent %}
<div class = "container">
<div class = "row">
<h1>#{{song.rank}}: {{song.title}} </h1>
</div>
<div class = "row ">
<div class = "col-sm">
<img src = {{song.cover}} alt = "No cover">
</div>
<div class = "col-sm">
<p>
<strong>{{song.releaseInfo}}</strong>
<br>
<br>
<strong>Artist:</strong> {{song.artist}}
<br>
<strong>Writer(s):</strong> {{song.writers}}
<br>
<strong>Producer(s):</strong> {{song.producer}}
<br>
<br>
{{song.description}}
</p>
</div>
</div>
</div>
{% endfor %}
{% for album in entry %}
<div class = "container">
<div class = "row">
<h1>#{{album.rank}}: {{album.title}} </h1>
</div>
<div class = "row ">
<div class = "col-sm">
<img src = {{album.cover}} alt = "No cover">
</div>
<div class = "col-sm">
<p>
<strong>Artist:</strong> {{album.artist}}
<br>
<strong>Label:</strong> {{album.label}}
<br>
<strong>Release Year:</strong> {{album.year}}
<br>
<br>
{{album.description}}
</p>
</div>
</div>
</div>
{% endfor %}
{% endblock %}
And the definitions of the models themselves, if that helps:
# Model to store a Rolling Stone top 500 song
class Songs(models.Model):
rank = models.IntegerField()
artist = models.CharField(max_length=50)
title = models.CharField(max_length=50)
cover = models.ImageField()
writers = models.CharField(max_length=100)
producers = models.CharField(max_length=100)
releaseInfo = models.CharField(max_length=100)
description = models.TextField()
used = models.BooleanField(default=False)
def __str__(self):
return self.title
# Model to store a Rolling Stone top 500 album
class Albums(models.Model):
rank = models.IntegerField()
artist = models.CharField(max_length=50)
title = models.CharField(max_length=50)
cover = models.ImageField()
label = models.CharField(max_length=100)
year = models.CharField(max_length=100)
description = models.TextField()
used = models.BooleanField(default=False)
def __str__(self):
return self.title
It works because you are filtering and retrieving .values(), which sort of means it's returning a queryset of probably 1.
In other words {% for song in ent %} is equivalent to for song in ent_queryset.
If you changed the filter to retrieve multiple songs/albums, you would see more than one song/album show up.
If you just want to retrieve one song/album, then you would need to do something like:
songChoice = Songs.objects.filter(rank = randomSong).values().first()
albumChoice = Albums.objects.filter(rank = randomAlbum).values().first()
entry = {'ent': songChoice, 'entry': albumChoice}
return render(request,'rollingStone/home.html', entry)
And then in your template you can access them directly:
{{ ent }} # this is your song obj
{{ ent.writers }}
{{ ent.artist }}
{{ entry }} # this is your album entry
Related
I have two models, ProjectNotes and ProjectNoteComments. ProjectNoteComments are related to ProjectNotes via a foreign key. I want to display the number of comments each note has on a listview. I am just learning Django and so far I have not been able to figure out how to retrieve and display the comment count.
My view:
(I do import count)
class ProjectNotesList(ListView):
model = ProjectNotes
template_name = 'company_accounts/project_notes.html'
comments = ProjectNotes.comments
def related_project(self, **kwargs):
project = get_object_or_404(Project, id=self.kwargs.get('pk'))
notes = ProjectNotes.objects.all
return notes
def get_context_data(self, **kwargs):
# Call the base implementation first to get a context
context = super().get_context_data(**kwargs)
context['project'] = get_object_or_404(Project, id=self.kwargs.get('pk'))
return context
commentscount = ProjectNotes.objects.annotate(num_comments=Count('comments'))
My template:
{% extends 'base.html' %}
{% block content %}
<div class="section-container container">
<h1>Notes for {{ project }}</h1>
{% if project.notes.all %}
{% for note in project.notes.all %}
<div class ="projectnotes-entry">
<div class="col-sm-8">
<div class="row-sm-6">
<div class="card mb-2">
<div class="card-body">
<div class="card-title">{{ note.title }}</div>
<div class="card-text">{{ note.body | safe | truncatewords:"20"|linebreaks }}
read more</div>
</div>
</div>
</div>
</div>
</div>
<h2>comments count</h2>
{{ commentscount }}
{% endfor %}
{% else %}
<p>No notes have been have been added yet.</p>
{% endif %}
</div>
{% endblock content %}
The models:
class ProjectNotes(models.Model):
title = models.CharField(max_length=200)
body = tinymce_models.HTMLField()
date = models.DateField(auto_now_add=True)
project = models.ForeignKey(Project, default=0, blank=True, on_delete=models.CASCADE, related_name='notes')
def __str__(self):
return self.title
class ProjectNoteComments(models.Model):
body = tinymce_models.HTMLField()
date = models.DateField(auto_now_add=True)
projectnote = models.ForeignKey(ProjectNotes, default=0, blank=True, on_delete=models.CASCADE, related_name='comments')
Short version:
{{ note.comments.all.count }} # possibly works also without 'all' but can't check right now
I've just answered similar problem with simple explanation of relationships.
https://stackoverflow.com/a/70955851/12775662
Read official docs, it's really rewarding. https://docs.djangoproject.com/en/4.0/topics/db/models/#relationships
I'm trying to set up magnific popup on django.
My goal is to have one main picture in the homepage overview gallery view, which when clicked, would open a popup with the related images from the same photoshoot i.e. images with the same ID or PK.
I tried to apply the following approach
but i just cannot get it to work, maybe someone could help me out in this
My models.py
class Item(models.Model):
name = models.CharField(blank=False, max_length=200)
category = models.ForeignKey(Category, blank=True, null=True, on_delete=models.SET_NULL)
order = models.IntegerField(blank=True, null=True)
active = models.BooleanField(blank=True, default=False)
objects = models.Manager()
class Meta:
verbose_name_plural = 'items'
def __str__(self):
return self.name
class ItemImage(models.Model):
image = ProcessedImageField(
blank=True,
null=True,
processors=[ResizeToFit(width=1680, upscale=False)],
format='JPEG',
options={'quality':90})
order = models.IntegerField(blank=True, null=True)
main = models.BooleanField(blank=True, default=False)
cover = models.BooleanField(blank=True, default=False)
item = models.ForeignKey(Item, related_name='items', blank=True, null=True, on_delete=models.SET_NULL)
objects = models.Manager()
class Meta:
verbose_name_plural = 'item images'
Views.py
def portraits(request):
port = ItemImage.objects.filter(item__category__slug='portraits', item__active=True, main=True,).order_by('item__order')
portall = ItemImage.objects.filter(item__category__slug='portraits', item__active=True).order_by('item__order')
context = {
'main_portraits': port,
'all_portraits': portall
}
return render(request, 'gallery/portraits.html', context)
and Template:
{% block content %}
<div class="grid">
{% for pic in main_portraits %}
<div class="item">
<div class="item">
<div class="outer-text">
<div class="text">
{{ pic.item.name }}
<p>Click to view gallery</p>
</div>
</div>
<a><img class="lazy" alt=""
sizes="(min-width:1400px) 1220px
(min-width:1000px) 1000px,
(min-width:500px) 700px,
(min-width:320px) 420px,
280px"
srcset="{{ pic.image_xs.url }} 280w,
{{ pic.image_s.url }} 420w,
{{ pic.image_m.url }} 700w,
{{ pic.image_l.url }} 1000w,
{{ pic.image_xl.url }} 1220w" />
</a> {{ pic.item.pk }}
</div>
<div class="lazy">
{% for p in all_portraits %}
{% endfor %}
</div>
</div>
{% endfor %}
</div>
{% endblock %}
I have set
z.item.pk
just as a test, to see if any of my manipulations result in the pk's to bunch up. For example the first for-loop returns a picture with PK "24", I need for the second for-lop to return only images with the same PK; and so for every image. I think the answer might be connected with _set.all function, just like in the related question above, but I cant seem to get it to work in my case. Feels like I'm missing something here.
current output:
<div class="grid">
<div class="item">
<div class="item">
<div class="outer-text">
<div class="text">
Palagā tītā
<p>Click to view gallery</p>
</div>
</div>
<a><img class="lazy" alt=""
sizes="(min-width:1400px) 1220px
(min-width:1000px) 1000px,
(min-width:500px) 700px,
(min-width:320px) 420px,
280px"
srcset="/media/CACHE/images/IMG_8329_3Vi8mYO_GD621ql/958ba5dbee5efe28fd2f5054b8f819e1.jpg 280w,
/media/CACHE/images/IMG_8329_3Vi8mYO_GD621ql/02d12ca7f0633fee2fc762cf96f7889e.jpg 420w,
/media/CACHE/images/IMG_8329_3Vi8mYO_GD621ql/ba5fa6633e92a288e3b2f47a713d64c2.jpg 700w,
/media/CACHE/images/IMG_8329_3Vi8mYO_GD621ql/fe0d559fef5b02434c43f841005d4961.jpg 1000w,
/media/CACHE/images/IMG_8329_3Vi8mYO_GD621ql/96d0e52dff14d1bc4b60bbec674565db.jpg 1220w" />
</a> 24
</div>
<div class="lazy">
</div>
</div>
You need prefiltered querysets containing the related images for every main image before handing over to the template.
def portraits(request):
ports = ItemImage.objects.filter(item__category__slug='portraits', item__active=True, main=True,).order_by('item__order')
for p in ports:
# You may not need the item__category__slug filter
# if there are only images of the same category
# associated with an item.
# Also, if you want to exclude the main image
# from the set of related images, you need to add the filter
# main=False
p.related_images = ItemImage.objects.filter(item__category__slug='portraits', item__id=p.item.id)
context = {
'main_portraits': ports,
}
return render(request, 'gallery/portraits.html', context)
Then you can loop over main_portraits in the template, and get the related images for each main image in a nested loop:
{% for mainp in main_portraits %}
{% for im in mainp.related_images %}
{# do something with the related images #}
{% endfor %}
{% endfor %}
You can break down the models like this it will make the querying easier.
# models.py
class Item(mdoels.Model):
name = models.CharField(blank=False, max_length=200)
category = models.ForeignKey(Category, blank=True, null=True, on_delete=models.SET_NULL)
...
display_image = models.ProcessedImageField(...)
class ItemImage(models.Model):
item = models.ForeignKey(Item, related_name='images', blank=True, null=True, on_delete=models.SET_NULL)
image = models.ProcessedImageField(...)
...
#views.py
def portraits(request):
items = Item.objects.filter(category__slug='portraits', active=True)
return render(request, 'gallery/portraits.html', context={items: items})
#template
{% for item in items %}
<h1> {{item.name}} </h1>
<img src={{item.display_image}} />
{% for item_image in item.images.all %}
<img src={{item_image.image}} />
{% endfor %}
{% endfor %}
I would like to add some Order details(DetailView) in the Order history page(ListView), See image example below ( I have made the image on photoshop). I was able to get the grey part (order list to show) But I am not able to get the item details to show in this page correctly. If I click View Order Detail it goes to detail page where I can show all this. But I need a small summary in the ListPage too. See example below. How do I change my views or templates to achieve this? See my views and templates below
Below is how I need my order history page to look like
Below are my my models.py
class Order(models.Model):
token = models.CharField(max_length=250, blank=True)
total = models.DecimalField(max_digits=6, decimal_places=2, verbose_name='USD Order Total')
emailAddress = models.EmailField(max_length=100, blank=True, verbose_name='Email Address')
created = models.DateTimeField(auto_now_add=True)
billingName = models.CharField(max_length=350, blank=True)
billingAddress1 = models.CharField(max_length=350, blank=True)
billingCity = models.CharField(max_length=100, blank=True)
billingZipcode = models.CharField(max_length=10, blank=True)
billingCountry = models.CharField(max_length=50, blank=True)
class OrderItem(models.Model):
product = models.CharField(max_length=250)
quantity = models.IntegerField()
price = models.DecimalField(max_digits=5, decimal_places=2, verbose_name='USD Price')
order = models.ForeignKey(Order, on_delete=models.CASCADE)
image = models.ImageField()
Below is my template
{% block body %}
<div>
<div class="text-center">
<br/>
<h1 class="text-center my_title">Order Purchase History</h1>
<br/>
{% if order_details %}
{% for order in order_details %}
<div class="row order_detail_div" >
<div class="col-md-2">
<b>Order Number: 1234{{ order.id }}</b><br/>
<small><em>Order Date: {{ order.created|date:"M d Y" }}</em></small>
</div>
<div class="col-md-1"></div>
<div class="col-md-3 text-left">
<b>Status: Paid</b><br/>
<b>Total items in Order: ()</b>
</div>
<div class="col-md-1"></div>
<div class="col-md-3 order_total_text">
<b>Order Total: ${{ order.total }}</b>
</div>
<div class="col-md-2 view_order_details">
<b>View Order Details</b>
</div>
</div>
{% for item in order_items %} <!-- This gets the order items from the Order -->
<div class="row order_item_detail_div">
<div class="col-md-2">
<img src="{{ item.image }}" >
</div>
<div class="col-md-2">
{{ item.product}}
</div>
<div class="col-md-2">
{{ item.id}}
</div>
<div class="col-md-2">
{{ item.quantity}}
</div>
<div class="col-md-2">
{{ item.price}}
</div>
</div>
{% endfor %}
<br/>
{% endfor %}
{% else %}
<p>
You do not have any orders yet.<br/><br/>
Add more recipes
</p>
{% endif %}
</div>
</div>
<br/>
<br/>
{% endblock %}
Views.py 1st try
Error: For some reason the print statement in terminal shows correctly but in the browser it shows. See image below code
class OrderHistory(LoginRequiredMixin, ListView):
model = Order
template_name = 'order/order_list.html'
def get_context_data(self, **kwargs):
context = super(OrderHistory, self).get_context_data()
context['order_details'] = Order.objects.filter(emailAddress=self.request.user.email) #The code is correct till here
order_details = Order.objects.filter(emailAddress=self.request.user.email)
for order in order_details:
print("Order items are", OrderItem.objects.filter(order=order))
context['order_items'] = OrderItem.objects.filter(order=order)
return context
The Order details in grey are correct but the OrderItems do not correspond to the order. It should be like in the 1st image(above)
Views.py 2nd try Error: I thought will do OrderItem.objects.all()) in the views.py and the forloop in the template will fix the view but below is the error I get
class OrderHistory(LoginRequiredMixin, ListView):
model = Order
template_name = 'order/order_list.html'
def get_context_data(self, **kwargs):
context = super(OrderHistory, self).get_context_data()
context['order_details'] = Order.objects.filter(emailAddress=self.request.user.email) #The code is correct till here
print("Order items are", OrderItem.objects.all())
context['order_items'] = OrderItem.objects.all()
return context
Again this is not correct these 2 items do not belong to Order. See the 1st image for how it should be. The grey part which contains order details is still correct
Its a bit confusing, but i guess i manage to get the points...
The problem is here... since Django is not dinamic, they will send your data after processing everything to your template... what you doing here is overring every value at your context['order_items'] so they will send to template only the last data.
for order in order_details:
context['order_items'] = OrderItem.objects.filter(order=order)
When you made the change to context['order_items'] = OrderItem.objects.all() without the forloop now you getting all Order Item without set any order... so when you try to show the OrderItem from first Order they will show all OrderItem.
The Sollution is use TEMPLATETAGS so that way you can filter your data while the HTML is processing...
So you need to filter your OrderItem based in your Order... since in your page you will show many orders and you must filter the OrderItem based in this Orders
create one folder called templatetags inside your app, create one file to be your templatetag (dont forget to create __init__.py file too) in that case we will call order_templatetags.py
app/templatetags/order_templatetags.py
from django import template
from .models import OrderItem
register = template.Library()
#register.filter
def filter_order_items(self):
return OrderItem.objects.filter(order__id=self.id)
IN YOUR HTML
<!-- IN TOP OF YOUR HTML (After Extends if you have it) PLACE THIS CODE -->
{% load order_templatetags %}
<!-- REST OF YOUR HTML CODE -->
{% for order in order_details %}
<!-- REST OF YOUR HTML CODE -->
{% for item in order|filter_order_items %} <!-- This gets the order items from the Order -->
<!-- YOUR HTML STUFFS -->
{% endfor %}
{% endfor %}
My Snippet: https://github.com/Diegow3b/django-utils-snippet/blob/master/template_tag.MD
Django Docs: https://docs.djangoproject.com/en/2.0/howto/custom-template-tags/
Well I did finally figure it out
models.py (Add related_name in order field)
class OrderItem(models.Model):
product = models.CharField(max_length=250)
quantity = models.IntegerField()
price = models.DecimalField(max_digits=5, decimal_places=2, verbose_name='USD Price')
order = models.ForeignKey(Order, on_delete=models.CASCADE, related_name="order_cushions")
image = models.ImageField()
views.py is
class OrderHistory(LoginRequiredMixin, ListView):
model = Order
template_name = 'order/order_list.html'
def get_context_data(self, **kwargs):
context = super(OrderHistory, self).get_context_data()
context['order_details'] = Order.objects.filter(emailAddress=self.request.user.email)
print("Order items are", OrderItem.objects.all())
context['order_items'] = OrderItem.objects.all()
return context
and finally in templates.py
{% for order in order_details %}
{% for item in order.order_cushions.all %} #this is the models related_name
{{item.image}} #this will get your image
{{item.product}}
{{item.price}}
{{item.quantity}} #decorate using bootstrap the way you like
{% endfor %}
{% endfor %}
My way was with a method inside Order returning a Queryset
models.py
class Order(models.Model):
...
def items(self):
return OrderItem.objects.filter(order=self)
Call items inside a loop
Orderlist.html
{% for order in order_details %}
{% for item in order.items %}
<!-- YOUR HTML STUFFS -->
{% endfor %}
{% endfor %}
I'm beginner on Django.
I have a project with the following models:
My Articles models:
class Post(models.Model):
title = models.CharField(max_length=200)
slug = models.SlugField(max_length=160)
content = models.TextField()
image = models.ImageField(upload_to=upload_location)
timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)
updated = models.DateTimeField(auto_now=True, auto_now_add=False)
categorie = models.CharField(max_length=200)
categorie = models.ForeignKey('categorie.Categorie')
publier = models.BooleanField()
My Portfolio categories models which is linked with my Article Model:
class Categorieport(models.Model):
title = models.CharField(max_length=200)
article = models.OneToOneField('posts.Post')
And finally, my portfolio models with all the photos:
class Portfolio(models.Model):
title = models.CharField(max_length=200)
image = models.ImageField(upload_to=upload_location)
timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)
updated = models.DateTimeField(auto_now=True, auto_now_add=False)
categorieportfolio = models.ForeignKey('Categorieport')
In one view and one template, i'd like to display information concerning the article and the portfolio related to the article.
I wrote the following view:
def portfolio(request, article=None):
portfolio = get_object_or_404(Categorieport, article=article)
image_portfolio = portfolio.portfolio_set.all()
return render(request, 'portfolio1.html', {'portfolio': portfolio, 'image_portfolio': image_portfolio})
And the following templates:
<div class="titre-display">
<h2>{{ portfolio.article.timestamp|date:"d E Y" }} / {{ portfolio.article.categorie}} </h2>
<h1>{{ portfolio.article.title}}</h1>
</div>
<div class="content-display">
<div class="content-display-main">
<div class="content-display-main-portfolio">
<div class="image-portfolio">
<a class="example-image-link" href="{{ image_portfolio.image.url }}" data-lightbox="example-set" data-title="{{image_portfolio.title}}">
</a>
I can access to information from my article but i can't access information from my portfolio. I tried it with the shell, and it works. I can't figure out why it doesn't work in my view and template.
Do you have any idea?
Thank you in advance
Singertwist
Your image_portfolio is a querySet, that's means is some kind of list, you have to use a loop to access the items and them access the properties:
<div class="content-display">
<div class="content-display-main">
<div class="content-display-main-portfolio">
<div class="image-portfolio">
{% for item_img in image_portfolio %}
<a class="example-image-link" href="{{ item_img.image.url }}" data-lightbox="example-set" data-title="{{item_img.title}}"></a>
{% endfor %}
Try this:
# views.py
def portfolio(request, article=None):
# first get the Post instance with slug = article (I'm assuming article passed as url argument, is a slug)
post = get_object_or_404(Post, slug=article)
# get the Categoriepost object based on a specifi article
categorie_port = get_object_or_404(Categorieport, article=post)
# image_portfolio is a QuerySet (that is a list of Portfolio objects)
image_portfolio = categorie_port.portfolio_set.all()
return render(request, 'portfolio1.html', {'portfolio': categorie_port, 'image_portfolio': image_portfolio})
Leave your HTML as is.
Hi thank you all for your answer.
So, I used a for loop for solving my case as mentioned previously.
Below, my code:
<div class="titre-display">
<h2>{{ portfolio.article.timestamp|date:"d E Y" }} / {{ portfolio.article.categorie}} </h2>
<h1>{{ portfolio.article.title}}</h1>
</div>
<div class="content-display">
<div class="content-display-main">
<div class="content-display-main-portfolio">
{% for photo in image_portfolio %}
<div class="image-portfolio">
<a class="example-image-link" href="{{ photo.image.url }}" data-lightbox="example-set" data-title="{{photo.title}}">
{% thumbnail photo.image "300x300" crop="center" as im %}
<img class="example-image" src="{{ im.url }}" alt=""/>
{% endthumbnail %}
</a>
<p>{{photo.title}}</p>
</div>
{% empty %}
<p>Aucun portfolio.</p>
{% endfor %}
</div>
</div>
And my views:
def portfolio(request, slug=None, article=None):
slug = get_object_or_404(Post, slug=slug)
portfolio = get_object_or_404(Categorieport, article=article)
image_portfolio = portfolio.portfolio_set.all()
return render(request, 'portfolio.html', {'portfolio': portfolio, 'image_portfolio': image_portfolio})
Thanks again for your help
Singertwist
I am creating a blog and have a many-to-many relationship between the posts and categories.
class Category(models.Model):
title = models.CharField(max_length=255)
slug = models.SlugField()
def __str__(self):
return self.title
class Post(models.Model):
title = models.CharField(max_length=255)
subtitle = models.CharField(max_length=255,null=True,blank=True)
published_date = models.DateTimeField(auto_now_add=True)
draft = models.BooleanField(default=True)
body = RichTextField(config_name='blog')
slug = models.SlugField()
categories = models.ManyToManyField(Category)
featured = models.BooleanField(default=False)
I am trying to retrieve the the list of categories associated to an individual post within the template so I can display those category titles at the bottom of the post.
Here is the template code which displays the posts properly but not the categories.
{% for post in blog_posts %}
<div class="post">
<div class="date">
{{post.published_date|date:"M"}}
<span class="day">{{post.published_date|date:"d"}}</span>
<span>{{post.published_date|date:"Y"}}</span>
</div>
<div class="entry">
<div class="page-header">
<h2 class="post-title">{{post.title}}</h2>
</div>
<blockquote>
<p><strong>{{post.subtitle}}</strong></p>
</blockquote>
<p>{{post.body|safe}}</p>
<div class="well well-small">
<i class="icon-th-list "></i> Categories:LIST CATEGORIES HERE
</div>
</div> <!--entry div-->
</div><!--post div-->
{% endfor %}
Does anyone have thoughts on how I could retrieve the categories for a specific post? I greatly appreciate the time and expertise.
You can access the categories with this
{% for category in post.categories.all %}
{{ category.title }}
{% endfor %}
I also recommend adding .prefetch_related('categories') to the queryset in your view to reduce the number of sql queries.