Reputation: 5
Id like to store a filtered queryset in a list and then iterate over the list in my template.
I have a list of tenants in my model stored like so:
class Tenant(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
telephone = models.CharField(max_length=30)
email = models.CharField(max_length=30)
contract_end = models.DateField(blank=False)
def __str__(self):
return u'%s %s' % (self.first_name, self.last_name)
View like so:
def expiry(request):
now = datetime.datetime.now()
tenant_queryset = Tenant.objects.all()
expired_list = []
for x in range(0, 12):
date = now + relativedelta(months=x)
expired = tenant_queryset.filter(
contract_end__year=date.year,
contract_end__month=date.month
)
expired_list.append(expired)
context = {"expired_list": expired_list}
return render(request, "expired_template.html", context)
Template:
{% for tenant in expired_list %}
{{ tenant.first_name }}<br>
{{ tenant.telephone }}<br>
{{ tenant.contract_end }}<br>
{% endfor %}
Im using a for loop in my view to go through the months of the year, then storing those results in a list.
I cant seem to get tenant.first_name, tenant.last_name, tenant.telephone and tenant.contract_end values to display in my template. Im guessing this is because Im already outputting the results of my filtered queryset to a list and its displaying those results rather than a 'reference', if that makes sense.
How can I go about this?
Thanks for the help.
Upvotes: 0
Views: 581
Reputation: 12086
That's because you are appending each time in your expired_list
a QuerySet
.
Change append
to this:
expired_list += expired
So that, you finally get a unified (flatten) QuerySet
(list).
Python (very simple) example:
list_1 = []
list_2 = [1, 2, 3]
list_1.append(list_2)
print(list_1) # [[1, 2, 3]]
list_1 = []
list_2 = [1, 2, 3]
list_1 += list_2
print(list_1) # [1, 2, 3]
Upvotes: 1