python - 如何使这个功能在django 的views.py 中工作?

标签 python html django

我想让这个 Destination() 函数使用多个变量,因为我不想一次又一次地编写它。我使它与两个变量相等,但它不起作用。如何解决这个问题?

def index(request):
    a,b = Destination()
    a.desc = 'Hello, How are you!'
    a.img = '01.jpg'

    b.desc = 'Hello, How are you!'
    b.img = '02.jpg'

    target = [a,b]

    context = {
     'target': target
    }
    return render(request, 'index.html', context)

最佳答案

如果你写 a, b = ... 你执行 iterable unpacking [PEP-3132] .由于 Destination 对象可能不可迭代,因此这行不通。

例如,您可以在此处使用列表理解生成两个 Destination,这甚至可以跳过第二次分配 target = [a, b] 的需要:

def index(request):
    <b>target</b> = a, b = <b>[</b>Destination() <b>for __ in range(2)]</b>
    a.desc = 'Hello, How are you!'
    a.img = '01.jpg'

    b.desc = 'Hello, How are you!'
    b.img = '02.jpg'

    context = {
     'target': target
    }
    return render(request, 'index.html', context)

鉴于 descDestination(..) 的构造函数的参数,您也可以省略它:

def index(request):
    target = a, b = [Destination(<b>desc='Hello, How are you!'</b>) for __ in range(2)]
    a.img = '01.jpg'
    b.img = '02.jpg'

    context = {
     'target': target
    }
    return render(request, 'index.html', context)

严格来说,您可以制作某种生成器,例如:

def generator(f, n, *args, **kwargs):
    return [f(*args, **kwargs) for __ in range(n)]

那么上面的可以替换为:

def index(request):
    target = a, b = <b>generator(</b>Destination, 2, desc='Hello, How are you!'<b>)</b>
    a.img = '01.jpg'
    b.img = '02.jpg'

    context = {
     'target': target
    }
    return render(request, 'index.html', context)

这因此略微减少了样板代码的数量,尽管它可能会降低可读性,因为现在读者需要先检查 generator 函数。

关于python - 如何使这个功能在django 的views.py 中工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56984757/

相关文章:

javascript - 将变量传递给 resize() jquery

django - 访问 Django 模型的父类

javascript - 无法在 Chrome 移动版 View 中从本地加载 PDF

python - 如何确保在 headless 模式 Firefox 驱动程序中截取的屏幕截图尺寸始终相同?

python - 是正则表达式错误还是我的代码错误?

python - 如何根据点在 python 中拆分字符串,忽略十进制值?

javascript - 使用 jquery 根据背景颜色对表格行进行排序

python - Django 中的计数字段?

python - Django:更新查询集中对象的顺序属性

python - 在 Python 命令行上定义函数时出现语法错误