python - Django 说 : too many values to unpack (expected 2)

标签 python django django-views

我正在使用 Django。在 upload_book 函数中,我为每本书生成一个 10 位代码,并通过代码(而不是主键)来识别和区分两本书。但是,我在 generate_code 函数中遇到错误:

ValueError at /main/upload_book/
too many values to unpack (expected 2)

这是带有所需导入的 generate_code() 函数:

import random, string
def generate_code(max_length):
    code = ''.join(random.choices(string.ascii_letters + string.digits, k=max_length))
    while len(Book.objects.filter(code)) != 0:
        code = ''.join(random.choices(string.ascii_letters + string.digits, k=max_length))
    return code

我在那里做了额外的处理,以防止两本书具有相同的代码,无论 629 种可能的组合出现这种情况的可能性有多低。 这是我的 upload_book() 函数:

@login_required
def upload_book(request):
    if request.method == 'POST':
        title = request.POST.get('title')
        description = request.POST.get('description')
        author = request.POST.get('author')
        code = generate_code(10)
        owner = request.user
        if 'thumbnail' in request.FILES:
            thumbnail = request.FILES['thumbnail']
        book = Book(title=title, description=description, author=author, thumbnail=thumbnail, owner=owner, code=code)
        book.save()
        return redirect("/main/all_books/")
    else:
        return render(request, 'main/upload_book.html')

以及 models.py 中我的 Book 模型:

class Book(models.Model):
    title = models.CharField(max_length=1000, blank=True)
    owner = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True)
    description = models.TextField()
    author = models.CharField(max_length=1000, blank=True, null=True)
    thumbnail = models.ImageField(upload_to='book_thumbnails', blank=True)
    creation_date = models.DateTimeField(default=timezone.now)
    status = IntegerField(default=1)
    min_age = models.IntegerField(blank=True, null=True)
    max_age = models.IntegerField(blank=True, null=True)
    code = models.CharField(blank=True, null=True, max_length=10)
    community = models.ForeignKey(Community, blank=True, null=True, on_delete=models.CASCADE)
    def __str__(self):
        return self.title

错误出现在 upload_book() 函数的这一行:

code = generate_code(10) 

这导致 generate_code() 函数中的这一行:

while len(Book.objects.filter(code)) != 0: 

这是错误及其回溯:

Internal Server Error: /main/upload_book/
Traceback (most recent call last):
  File "/opt/homebrew/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner
    response = get_response(request)
  File "/opt/homebrew/lib/python3.9/site-packages/django/core/handlers/base.py", line 181, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/opt/homebrew/lib/python3.9/site-packages/django/contrib/auth/decorators.py", line 21, in _wrapped_view
    return view_func(request, *args, **kwargs)
  File "/Users/adithraghav/Documents/Work/centel/books/main/views.py", line 101, in upload_book
    code = generate_code(10)
  File "/Users/adithraghav/Documents/Work/centel/books/main/views.py", line 24, in generate_code
    while len(Book.objects.filter(code)) != 0:
  File "/opt/homebrew/lib/python3.9/site-packages/django/db/models/manager.py", line 85, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/opt/homebrew/lib/python3.9/site-packages/django/db/models/query.py", line 941, in filter
    return self._filter_or_exclude(False, args, kwargs)
  File "/opt/homebrew/lib/python3.9/site-packages/django/db/models/query.py", line 961, in _filter_or_exclude
    clone._filter_or_exclude_inplace(negate, args, kwargs)
  File "/opt/homebrew/lib/python3.9/site-packages/django/db/models/query.py", line 968, in _filter_or_exclude_inplace
    self._query.add_q(Q(*args, **kwargs))
  File "/opt/homebrew/lib/python3.9/site-packages/django/db/models/sql/query.py", line 1393, in add_q
    clause, _ = self._add_q(q_object, self.used_aliases)
  File "/opt/homebrew/lib/python3.9/site-packages/django/db/models/sql/query.py", line 1412, in _add_q
    child_clause, needed_inner = self.build_filter(
  File "/opt/homebrew/lib/python3.9/site-packages/django/db/models/sql/query.py", line 1283, in build_filter
    arg, value = filter_expr
ValueError: too many values to unpack (expected 2)

我不知道为什么会发生这种情况。在另一个问题中,接受的答案提到,当使用 split() 并返回两个以上元素时会发生这种情况。我将由 random.choices(string.ascii_letters + string.digits, k=max_length) 生成的列表元素加入到一个字符串中。当我在 Python IDLE shell 中打印 ''.join(random.choices(string.ascii_letters + string.digits, k=max_length)) 时,它会返回一个字符串。那么这里有什么问题呢?

最佳答案

当您在模型对象上使用 filter() 方法时,您也必须传递字段名

所以改变这一行

while len(Book.objects.filter(code)) != 0:

while Book.objects.filter(code=code).count() != 0:

关于python - Django 说 : too many values to unpack (expected 2),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70401271/

相关文章:

python - matplotlib 中 LaTeX 轴标签的粗体字重

javascript - 这是使用 nodejs 的好场景吗?

django - 如何从其他表获取数据,例如序列化器类 django-rest-framework 中的左连接

python - Django unittest 只读测试数据库

django - 'QuerySet' 对象在使用 timesince 时没有属性 'year'

python - Django - 通用 View 中的查询集与模型

python - 以下约束的 PuLP 程序 min(a,b) > min(x,y)

python脚本按行连接值并删除相同的值

python - 适用于 python2.7 谷歌应用引擎的云任务 API

Django 不会上传和保存文档