有关基本用户模型Django的Queryset问题

时间:2019-09-24 17:11:53

标签: django primary-key django-users

使用Django基本用户模型。使用基本模型pk时出现重复错误。不知道为什么我的应用程序似乎无法弄清楚哪个用户在发表评论。

def view_api(request):
    user = request.user
    if request.method == 'POST':
        if request.user.is_active:
            price, created = Model.objects.get_or_create(
            user=User.objects.filter(pk=user.pk),
            anonymous_user=False,
            comments=request.POST.get('comments')
            )

错误:

The QuerySet value for an exact lookup must be limited to one result using slicing.

跟踪:

File "/Users/~/query.py" in get_or_create
  538.             return self.get(**kwargs), False

File "/Users/~/query.py" in get
  402.         num = len(clone)

File "/Users/~/query.py" in __len__
  256.         self._fetch_all()

File "/Users/~/query.py" in _fetch_all
  1242.             self._result_cache = list(self._iterable_class(self))

File "/Users/~/query.py" in __iter__
  55.         results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size)

File "/Users/~/compiler.py" in execute_sql
  1087.             sql, params = self.as_sql()

File "/Users/~/compiler.py" in as_sql
  489.                 where, w_params = self.compile(self.where) if self.where is not None else ("", [])

File "/Users/~/compiler.py" in compile
  405.             sql, params = node.as_sql(self, self.connection)

File "/Users/~/where.py" in as_sql
  81.                 sql, params = compiler.compile(child)

File "/Users/~/compiler.py" in compile
  405.             sql, params = node.as_sql(self, self.connection)

File "/Users/~/related_lookups.py" in as_sql
  130.         return super().as_sql(compiler, connection)

File "/Users/~/lookups.py" in as_sql
  163.         rhs_sql, rhs_params = self.process_rhs(compiler, connection)

File "/Users/~/" in process_rhs
  257.                     'The QuerySet value for an exact lookup must be limited to '

Exception Type: ValueError at /api/voting/
Exception Value: The QuerySet value for an exact lookup must be limited to one result using slicing.

1 个答案:

答案 0 :(得分:2)

QuerySet是对象的集合。但是将User的集合(即使只包含一个用户)传递到user字段也没有多大意义。

无论如何您都不需要在这里使用QuerySet:您可以只使用request.user本身,例如:

def view_api(request):
    user = request.user
    if request.method == 'POST':
        if request.user.is_active:
            price, created = Model.objects.get_or_create(
                user=user
                anonymous_user=False,
                comments=request.POST.get('comments')
            )
    # …