Django 说:要解压的值太多(预期为 2)

Django says: too many values to unpack (expected 2)

我正在使用 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')

我的 Book 模型在 models.py 中:

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() 并且 returns 超过两个元素时会发生这种情况。我将 random.choices(string.ascii_letters + string.digits, k=max_length) 生成的列表的元素连接到一个字符串中。当我在 Python IDLE shell 中打印 ''.join(random.choices(string.ascii_letters + string.digits, k=max_length)) 时,它 returns 一个字符串就可以了。那么这里的问题是什么?

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

所以改变这一行

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

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