简体   繁体   中英

How to modify Django query_set before serving it in a ListView

I have a Django project with a database of Song Objects that users can search through.

My models.py looks like this:

class Songs(models.Model):

    title = models.CharField(max_length=100)
    artist = models.CharField(max_length=100)
    link = models.CharField(max_length=255, unique=True)
    album = models.CharField(max_length=100)
    duration = models.CharField(max_length=40)  # Duration in num_secs

and my views.py looks like this:

class ResultsView(ListView):

    template_name = os.path.join(APPNAME, "results.html")
    model = Songs
    context_object_name = 'results'
    paginate_by = 60
    ordering = ['title']

    def get_context_data(self, **kwargs):

        context = super(ResultsView, self).get_context_data(**kwargs)
        context['query'] = self.request.GET.get('query')
        return context

    def get_queryset(self, **kwargs):

        query = self.request.GET.get('query')
        query_set = Songs.objects.all()
        results = query_set.filter(title__icontains=query)
        return list(results)

And my results.html template looks like this:

{% if results %}
    <div class="container-fluid">
        <div class="row">
    {% for result in results %}
        <div class="col-md-2 result-col">
            <a data-toggle="tooltip" title="{{ result.title }}" target="_blank" href="/song/{{ result.id }}">
                <div class="result-text">{{ result.title }} </div>
                <div class="result-dur">{{ result.duration }}</div>
            </a>
        </div>

        {% endfor %}
        </div>
    </div>
{% else %}
    <h2>No Results</h2>
{% endif %}

Due to the way the data is initially stored in my DB, the duration of each song is stored as the number of seconds, ie a song that is 2 minutes long is stored with a duration of 120. However, I want to display it on the template in the format: "hh:mm:ss".

How can I modify my ResultsView class so that I can parse the duration field of all of the objects in my query_set so that they have a more readable duration?

Note: to be 100% clear, I know how to do the actual conversion, using strftime . What I don't know, is how to access the Song.duration fields in my ResultsView.

You could add a method or property to your model:

@property
def converted_time(self):
    return <your converted time>

And in your template {{ result.converted_time }}

You can just use a custom template tag.

Ref

snippet

@register.filter()
def formatSeconds(s):
    mins = math.floor(s / 60);
    secs = math.floor(s - (mins * 60)); 
    return "%d:%02d" % (mins, secs);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM