How can I print query set element in Django Template?

自作多情 提交于 2021-01-27 12:53:43

问题


I have this code in my template file

{{markets|getSpiderItem:spider.id}}

Mysql has market_timezone and market_location and it connects to another table with spider_id so I filtered as follow:

@register.filter
def getSpiderItem(datas, spider_id):
    return datas.filter(spider=spider_id)

I am getting this output:

<QuerySet [{'market_timezone': 'Turkey', 'market_location': 'Nigde'}]>          

I want to print this QuerySet item on Django Template separately.

This function has already 2 for loop so I want to print just 1 time. I don't wanna use for loop like this:

{% for market in markets|getSpiderItem:spider.id %}

I want something like this but I couldn't figure out:

For Example:

{{markets|getSpiderItem:spider.id|market_timezone}} # I don't know the true way.

回答1:


this is ok

{{markets|getSpiderItem:spider.id|market_timezone}}

modify getSpiderItem()

@register.filter
def getSpiderItem(datas, spider_id):
    return iter(datas.filter(spider=spider_id))

define filter market_timezone():

@register.filter
def market_timezone(iitem):
    return next(iitem).market_timezone

Expected content: Turkey



来源:https://stackoverflow.com/questions/63722225/how-can-i-print-query-set-element-in-django-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!