Question

I have two objects with one-to-many relationship:

from django.db import models

class DownloadItem(models.Model):
    name = models.CharField(max_length=200)
    description = models.CharField(max_length=200)
    downloadItem = models.ImageField(upload_to='./images/downloadItems', blank=True)

    def __unicode__(self):
        return self.name

class DownloadItemSample(models.Model):
    photo = models.ImageField(upload_to='./images/downloadItemsSample', blank=True)
    downloadItem = models.ForeignKey(DownloadItem, blank=True, null=True)
    order = models.IntegerField(default=0)

And in my view I am doing the following:

from django.shortcuts import render
from mainstore.models import DownloadItem

def index(request):
    downloads_list = DownloadItem.objects.all()
    context = {'downloads_list': downloads_list}
    return render(request, 'mainstore/index.html', context)

In my template I would like to get the following:

{{ downloads_list.downloadItemSample_set.all().order_by('order')[0] }}

I also would like to iterate over the array, but for this sample I am using the index 0.

I was thinking to write a custom template tag, but I think this isn't the best way to do this. I think I can write a method for the DownloadItem model which accepts an index and returns the correct DownloadItemSample object, but currently I couldn't create this one neither.

What would be the best way to solve this problem?

Was it helpful?

Solution

You would never be able to achieve downloads_list.downloadItemSample_set as downloads_list is a queryset.

One way to achieve this would be:

{% for download in downloads_list %}
    {{ download.get_sample_by_order }}
{% endfor %}

Here get_sample_by_order is a helper method in the class DownloadItem which returns the value we need.

class DownloadItem(models.Model):
    name = models.CharField(max_length=200)
    description = models.CharField(max_length=200)
    downloadItem = models.ImageField(upload_to='./images/downloadItems', blank=True)

    def __unicode__(self):
        return self.name

    def get_sample_by_order(self):   
        if self.downloaditemsample_set.count():
            return self.downloaditemsample_set.order_by('order')[0]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top