как исправить объект «Запрос» не имеет атрибута «содержит_колонки_референции» ошибка - PullRequest
0 голосов
/ 18 мая 2019

Поскольку я пытаюсь вставить некоторые данные с помощью POST-запроса в базу данных mysql, я получаю сообщение об ошибке, сообщающее, что у объекта AttributeError 'Query' нет атрибута 'contains_column_references', он выдает ошибку:

Traceback:

File "/Users/asp/Desktop/learning platform/env/lib/python3.7/site-packages/django/core/handlers/exception.py" in inner
  35.             response = get_response(request)

File "/Users/asp/Desktop/learning platform/env/lib/python3.7/site-packages/django/core/handlers/base.py" in _get_response
  128.                 response = self.process_exception_by_middleware(e, request)

File "/Users/asp/Desktop/learning platform/env/lib/python3.7/site-packages/django/core/handlers/base.py" in _get_response
  126.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/Users/asp/Desktop/learning platform/env/lib/python3.7/site-packages/django/contrib/auth/decorators.py" in _wrapped_view
  21.                 return view_func(request, *args, **kwargs)

File "/Users/asp/Desktop/learning platform/learningPlatform/contents/views.py" in create_content
  31.                 content.save()

File "/Users/asp/Desktop/learning platform/env/lib/python3.7/site-packages/django/db/models/base.py" in save
  729.                        force_update=force_update, update_fields=update_fields)

File "/Users/asp/Desktop/learning platform/env/lib/python3.7/site-packages/django/db/models/base.py" in save_base
  759.             updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)

File "/Users/asp/Desktop/learning platform/env/lib/python3.7/site-packages/django/db/models/base.py" in _save_table
  842.             result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)

File "/Users/asp/Desktop/learning platform/env/lib/python3.7/site-packages/django/db/models/base.py" in _do_insert
  880.                                using=using, raw=raw)

File "/Users/asp/Desktop/learning platform/env/lib/python3.7/site-packages/django/db/models/manager.py" in manager_method
  82.                 return getattr(self.get_queryset(), name)(*args, **kwargs)

File "/Users/asp/Desktop/learning platform/env/lib/python3.7/site-packages/django/db/models/query.py" in _insert
  1125.         return query.get_compiler(using=using).execute_sql(return_id)

File "/Users/asp/Desktop/learning platform/env/lib/python3.7/site-packages/django/db/models/sql/compiler.py" in execute_sql
  1280.             for sql, params in self.as_sql():

File "/Users/asp/Desktop/learning platform/env/lib/python3.7/site-packages/django/db/models/sql/compiler.py" in as_sql
  1233.                 for obj in self.query.objs

File "/Users/asp/Desktop/learning platform/env/lib/python3.7/site-packages/django/db/models/sql/compiler.py" in <listcomp>
  1233.                 for obj in self.query.objs

File "/Users/asp/Desktop/learning platform/env/lib/python3.7/site-packages/django/db/models/sql/compiler.py" in <listcomp>
  1232.                 [self.prepare_value(field, self.pre_save_val(field, obj)) for field in fields]

File "/Users/asp/Desktop/learning platform/env/lib/python3.7/site-packages/django/db/models/sql/compiler.py" in prepare_value
  1162.             if value.contains_column_references:

Exception Type: AttributeError at /contents/create
Exception Value: 'Query' object has no attribute 'contains_column_references'
traceback

from django.db import models
from lessons.models import Lessons
from django.utils.datastructures import MultiValueDictKeyError
class Contents(models.Model):
material_title = models.TextField()
content = models.TextField()
lesson_id = models.ForeignKey(Lessons,on_delete= models.CASCADE)

Следующий код получает параметры запроса POST и вставляет их в базу данных

 def create_content(request):
print("=================== create_content=============================")


if request.method == 'POST':
    if request.POST['lesson_id'] and request.POST['content'] and request.POST['material_title']:

        if request.POST['lesson_id']!='' and request.POST['content']!='' and request.POST['material_title']!='':



            ls = Lessons.objects

            lessons = Lessons.objects.filter(id=request.POST['lesson_id'])
            contents = Contents.objects.create(content=request.POST['content'],lesson_id_id=lessons,material_title=request.POST['material_title'])

            # contents.save()
            print("=======================")
            topic = Courses.objects.filter(userId=request.user)
            materialsbylesson = Lessons.objects



            return render(request,'contents_create.html', {'error':'Lesson Has been created successfully','topics':topic,'lessons':materialsbylesson})

        else:
            print("not all Available else statement3")
            topic = Courses.objects.filter(userId=request.user)
            materialsbylesson = Lessons.objects


            wikidata = Wikidata.objects
            return render(request,'contents_create.html', {'error':'Lesson Has been created successfully','topics':topic,'lessons':materialsbylesson})
    else:

        print("not all Available else statement2")
        print(request.POST['content'])
        topic = Courses.objects.filter(userId=request.user)
        materialsbylesson = Lessons.objects


        wikidata = Wikidata.objects
        return render(request,'contents_create.html', {'error1':'some inserted data is missing','topics':topic,'lessons':materialsbylesson})


else:
    # user = User.objects.get(username = request.POST['username'])
    try:
        # MARK get topics by user
        # MARK get lessons by topic
        print("==================================not post request")

        topic = Courses.objects.filter(userId=request.user)
        lessonsByTopic = Lessons.objects
        lessonsByUser = []
        for topicls in topic:
            lessons_hierarchy = Lessons.objects
            level_lesson = 1
            for lesson_hierarchy in lessons_hierarchy.all():
                if lesson_hierarchy.topic_id_id == topicls.id:
                    lessonsByUser.append(lesson_hierarchy)

        print("//////////////////////////////////////////////////////==")
        print(topic)
        print(lessonsByUser)
        # print(lessonsByTopic)
        print("//////////////////////////////////////////////////////==")
        # wiki_topic_id = topic.id
        # lesson = Lessons.objects

        return render(request,'contents_create.html',{'topics':topic,'lessons':lessonsByTopic,'ls':lessonsByUser})
    except Courses.DoesNotExist:
        print("except post request")
        print("does not exit")
        return render(request,'contents_create.html')

1 Ответ

0 голосов
/ 19 мая 2019

при создании нового контента должно быть так:

 contents = Contents.objects.create(content=request.POST['content'], lesson_id_id =request.POST['lesson_id'],material_title=request.POST['material_title'])
...