Young Code
Young Code

Reputation: 21

How to get a single object from a related model in django template

I have two models (Item and Album). Album has a foreign key pointing to Item like this

class Item(models.Model):
    name = models.CharField(max_length=50)
    price = models.IntegerField()

and

class Album(models.Model):
     photo = ImageField(upload_to=item_directory_path)
     caption = models.CharField(max_length=100, blank=True)
     item = models.ForeignKey(Item, on_delete=models.CASCADE)
     default = models.BooleanField(default=True)

In my template

             {% for item in item_tags %}        
                    <div class="item-dock">
                        <a href="{{item.name}}">
                            <img src="{{item.album_set.photo.filter(default=True)}}" class="img-responsive">
                            <p class="item-name text-center">{{item.name|capfirst}}</p>
                        </a>

Now the real issue is. Given that querying on a related model will always return a queryset. How can I retrieve a single object(in this case, a single photo from this queryset where the "default=True") from the Album model for an Item in my template.

I know about queryset and related manager!

Any help, suggestions will be much appreciated

Upvotes: 2

Views: 2198

Answers (2)

Ajmal Noushad
Ajmal Noushad

Reputation: 946

You can use a custom template filter for this: Details about creating and using custom template tags and filters can be found here: https://docs.djangoproject.com/en/1.11/howto/custom-template-tags/

from django import template

register = template.Library()


def default_image(queryset):
    return queryset.get(default=True).photo.url

register.filter('default_image', default_image)

You can use it in the template like this:

{{ item.album_set|default_image }}

Remember you need to {% load your_custom_template_tags %} before using the the filter

Upvotes: 0

hspandher
hspandher

Reputation: 16733

Just query the first element if that would suffice.

# something like this in your template
{% item.album_set.first.photo %}

Upvotes: 1

Related Questions