Django Interactive Shell API Fails

Asked 2 years ago, Updated 2 years ago, 453 views

Prerequisites/What you want to achieve
I am working on a tutorial on Django.
I was referring to the following site to use the command to call the interactive shell and access the database API, but an error occurred:Please tell me the solution.

https://docs.djangoproject.com/ja/4.0/intro/tutorial02/

Problems/Error Messages you are experiencing

>>>from polls.models import Choice, Question
>>Question.objects.all()
<QuerySet[<Question:Question object(1)>]>
>>Question.objects.filter(id=1)
<QuerySet[<Question:Question object(1)>]>
>>Question.objects.filter(question_text__startswith='What')
Traceback (most recent call last):
  "<console>", line 1, in <module>
  "\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\manager.py", line85, inmanager_method
    return getattr(self.get_queryset(),name)(*args,**kwargs)
  "\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\query.py", line 1071, filter
    return self._filter_or_exclude (False, args, kwargs)
  "\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\query.py", line 1089, in_filter_or_exclude
    clone._filter_or_exclude_inplace(negotiate, args, kwargs)
 "\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\query.py", line 1096, in_filter_or_exclude_inplace
    self._query.add_q(Q(*args,**kwargs))
 "\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\sql\query.py", line 1502, add_q
     cause,_=self._add_q(q_object,self.used_alias)
 "\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\sql\query.py", line 1532, in_add_q
     child_clause, needed_inner=self.build_filter(
  "\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\sql\query.py", line 1377, inbuild_filter
      looksups, parts, rejected_expression=self.solve_lookup_type(arg)
  "\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\sql\query.py", line 1187, insolve_lookup_type
       _,field,_,lookup_parts=self.names_to_path(lookup_splitted,self.get_meta())
   "\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\sql\query.py", line 1677, names_to_path
       raise FieldError(
    django.core.exceptions.FieldError: Cannot resolve keyword'question_text' into field.Choices are:id

Affected Source Code
I put ☆ where the error is occurring.

manaper.py line85

def check(self,**kwargs):
    return [ ]

@classmethod
def_get_queryset_methods(cls, queryset_class):
    def create_method(name,method):
        def manager_method(self, *args, **kwargs):
         ☆return getattr(self.get_queryset(),name)(*args,**kwargs)

    manager_method.__name__=method.__name__
    manager_method.__doc__=method.__doc__
    return manager_method

new_methods={}
for name, method inspect.getmembers(
    queryset_class,predicate=inspect.isfunction
):
    # Only copy missing methods.
    if hasattr(cls,name):
        continue
    # Only copy public methods or methods with the attribute
    # queryset_only=False.
    queryset_only=getattr(method, "queryset_only", None)
    if queryset_only or(queryset_only is None and name.startswith("_")):
        continue
    # Copy the method on to the manager.
    new_methods[name] = create_method(name,method)
return new_methods

query.py line 1071, 1089, 1096

def all(self):
"""
Return a new QuerySet that is a copy of the current one. This allows a
QuerySet to proxy for a model manager in some cases.
"""
return self._chain()

def filter(self, *args, **kwargs):
    """
    Return a new QuerySet instance with the args ANDed to the existing
    set
    """
    self._not_support_combined_queries("filter")
 ☆ return self._filter_or_exclude (False, args, kwargs)

def exclude(self, *args, **kwargs):
    """
    Return a new QuerySet instance with NOT(args) ANDED to the existing
    set
    """
    self._not_support_combined_queries("exclude")
    return self._filter_or_exclude (True, args, kwargs)

def_filter_or_exclude(self, negate, args, kwargs):
    if(args or kwargs) and self.query.is_sliced:
        raise TypeError("Cannot filter a query once a slice has been taken.")
    clone=self._chain()
    if self._defer_next_filter:
        self._defer_next_filter=False
        clone._deferred_filter=negotiate, args, kwargs
    else:
     ☆clone._filter_or_exclude_inplace(negotiate, args, kwargs)
    return clone

def_filter_or_exclude_inplace(self, negate, args, kwargs):
    if negate:
        self._query.add_q(~Q(*args,**kwargs))
    else:
     ☆self._query.add_q(Q(*args,**kwargs))
    

query.py line 1577

defusing(self, alias):
    US>"Select which database this QuerySet should execute again."
    clone=self._chain()
 ☆clone._db = alias
    return clone

query.py line 1187

def select_related (self, *fields):
"""
Return a new QuerySet instance that will select related objects.

If fields are specified, they must be ForeignKey fields and only those
related objects are included in the selection.

If select_related (None) is called, clear the list.
"""
self._not_support_combined_queries("select_related")
if self._fields is not None:
    raise TypeError(
        "Cannot call select_related() after.values() or.values_list()"
    )

obj=self._chain()
if fields==(None,):
 ☆obj.query.select_related = False
elif fields:
    obj.query.add_select_related (fields)
else:
    obj.query.select_related=True
return obj

query.py line 1677

def_clone(self):
    """Same as QuerySet._clone()"
    c=self.__class__(
        self.raw_query,
        model=self.model,
        query=self.query,
        params=self.params,
        translations = self.translations,
        using = self._db,
        hints = self._hints,
    )
    c._prefetch_related_lookups=self._prefetch_related_lookups[:]
    return c
☆
    def_fetch_all(self):
        if self._result_cache is None:
            self._result_cache=list(self.iterator())
        if self._prefetch_related_lookups and not self._prefetch_done:
            self._prefetch_related_objects()

Other

>>Question.objects.all()
<QuerySet [<Question: What's up?>]>
>>Question.objects.filter(id=1)
<QuerySet [<Question: What's up?>]>

python django

2022-09-30 22:04

1 Answers

Problems/Error Messages you are experiencing may be the second interaction shell to try playing with the API on the reference page.
The following is the back of the description.

Save your changes and run python manage.py shell again to start a new Python dialog shell:

The first part of the problem/error message that you are experiencing should be what other indicates at the end of the questionnaire.

Possible problems and causes include one of the following or a combination of them:

  • Try playing with the API's first interaction shell was not done properly.
    Whether you have set a string or date or subsequent q.save()?

  • You have not edited the polls/models.py file (such as the _str__() method or import after working on the first interaction shell in the same location

    ).
  • I made a mistake editing the polls/models.py file after working with the first interaction shell in the same location.
    For example, polls/https://docs.djangoproject.com/ja/4.0/intro/tutorial02/ file created by creating the model at the beginning of the page has been replaced with #... and deleted, or simply typeo when adding.

Playing with API's first interaction shell was not done properly.
Whether you have set a string or date or subsequent q.save()?

You have not edited the polls/models.py file (such as the _str__() method or import after working on the first interaction shell in the same location).

You edited the polls/models.py file incorrectly after working with the first interaction shell in the same location.
For example, polls/https://docs.djangoproject.com/ja/4.0/intro/tutorial02/ file created by creating the model at the beginning of the page has been replaced with #... and deleted, or simply typeo when adding.

Each source code presented in the appropriate source code is Django's own source code, so it doesn't make much sense to explain the question.

As @quickquip commented, the important thing is the contents of the polls/models.py file created and edited in the Tutorial article, so please present and check it.


2022-09-30 22:04

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.