如何在views.py函数中循环

时间:2019-07-16 06:53:26

标签: python html django

我只是想简化它,并想在views.py中创建一个循环,而不是编写每个项目。但这是行不通的。 Destinationmodels.py中的一类,我正在从数据库中获取数据。

from django.shortcuts import render
from . models import Destination
from django.db.models import Q

def index(request):
    query = request.GET.get('srh')
    if query:
        match = Destination.filter(Q(desc_icontains=query))

    # instead of writing this
    target1 = a, b= [Destination() for __ in range(2)]
    a.img = 'Article.jpg'
    b.img = 'Micro Tasks.jpeg'

    a.desc = 'Article Writing'
    b.desc = 'Micro Tasks'

    # I am trying to make a loop but it is not working.
    target1 = Destination.objects.all()
    for field in target1:
        [Destination(img = f'{field.img}', title = f'{field.title}') for __ in range(2)]

0 个答案:

没有答案