天天看點

buglist: django-mysql 增删改查功能

錯誤清單:

1、Invalid block tag on line 13: 'article.title', expected 'empty' or 'endfor'. Did you forget to register or load this tag?

2、{% include "article.html" %}引入頁面  為什麼内容為空,單獨建立一個url 打開就沒問題

3、django  多個條件查詢 TypeError: Object of type 'QuerySet' is not JSON serializable

4、django  多個條件查詢 django.core.exceptions.FieldError: Cannot resolve keyword 'depart' into field. Choices are: author, id, name

5、django  多個條件查詢 django.core.exceptions.FieldError: Related Field got invalid lookup: contains

6、module.py 反向關聯報錯

7、多對多關聯 ERRORS:<class 'proApp.admin.AuthorAdmin'>: (admin.E109) The value of 'list_display[8]' must not be a ManyToManyField. 

8、通過接口擷取資料庫資料,某字段是多對多關系,報錯TypeError: Object of type 'ManyRelatedManager' is not JSON serializable

9、通過接口擷取資料庫資料,某字段是一對多關系,報錯TypeError: Object of type 'Publisher' is not JSON serializable

10、多對多 修改資料:TypeError: Direct assignment to the forward side of a many-to-many set is prohibited. Use author.set() instead.

11 、主鍵由自增改為手動:django.db.utils.InternalError: (1833, "Cannot change column 'id': used in a foreign key constraint 'proApp_author_book_book_id_b4feaab6_fk_proApp_book_id' of table 'python_sql.proapp_author_book'")

1、Invalid block tag on line 13: 'article.title', expected 'empty' or 'endfor'. Did you forget to register or load this tag?

buglist: django-mysql 增删改查功能
<ul>

    {% for article in article_list %}

        <li>

            <h3>{{ article.title }}</h3>

            <p>{{ article.content }}</p>

        </li>

    {% endfor %}

</ul>
           

注意:

for循環語句 :{%  %}

字段取值: {{   }}

效果圖如下所示:

buglist: django-mysql 增删改查功能

2、{% include "article.html" %}

引入頁面  為什麼内容為空,單獨建立一個url 打開就沒問題

buglist: django-mysql 增删改查功能
buglist: django-mysql 增删改查功能
buglist: django-mysql 增删改查功能
buglist: django-mysql 增删改查功能
def showArticle(request):

    from proApp import models

    article_list = models.Article.objects.all()

    return render(request,"article.html",{"article_list":article_list})
           

解決辦法:

不需要在 def 中return render(傳回的是代碼片段)。正确代碼如下:

def addArticle(request):

    title = request.POST.get("title")

    content = request.POST.get("content")

    dic = {'title': title, 'content': content}

    models.Article.objects.create(**dic)

    return HttpResponse("文章添加成功!")          // 傳回的即是ajax 獲得data
           

3、django  多個條件查詢

問題1:TypeError: Object of type 'QuerySet' is not JSON serializable

解決辦法: https://blog.csdn.net/teavamc/article/details/77777301

問題2:中文獲得的是unicode

buglist: django-mysql 增删改查功能

解決辦法:序列化時添加第三個參數 ensure_ascii

articleList = serializers.serialize("json",models.Article.objects.filter(title__contains=title).filter(content__contains=content),ensure_ascii=False)

buglist: django-mysql 增删改查功能

問題3:ajax擷取的list資料 并不是對象形式 https://www.jb51.net/article/136971.htm

解決辦法:字元串 -> 字典形式

articleList = serializers.serialize("json",models.Article.objects.filter(title__contains=title).filter(content__contains=content),ensure_ascii=False)

articleList = json.loads(articleList)

data = {

    'ret': {

        'success': True,

        'retCode': 200,

        'retMsg': "文章查詢成功!"

    },

    'list': articleList

}

return HttpResponse(json.dumps(data), content_type='application/json; charset=utf-8')
           
buglist: django-mysql 增删改查功能

4、django  多個條件查詢 

問題:django.core.exceptions.FieldError: Cannot resolve keyword 'depart' into field. Choices are: author, id, name

buglist: django-mysql 增删改查功能
buglist: django-mysql 增删改查功能

解決辦法:

表連錯了 

buglist: django-mysql 增删改查功能

5、django  多個條件查詢

問題:django.core.exceptions.FieldError: Related Field got invalid lookup: contains

解決辦法:contains 是模糊搜尋,這裡部門值是絕對搜尋

depart = request.POST.get("depart")

search_sql = search_sql.filter(name__contains=name).filter(depart=depart)
           

6、module.py 反向關聯報錯:

buglist: django-mysql 增删改查功能

解決辦法: 添加 related_name

class Book(models.Model):

    author = models.ManyToManyField(Author,null=True,related_name='book_author')


class Author(models.Model):

    book = models.ManyToManyField('Book',null=True,related_name='author_book')
           

7、ERRORS:<class 'proApp.admin.AuthorAdmin'>: (admin.E109) The value of 'list_display[8]' must not be a ManyToManyField. 

admin.py: list_display 不可以輸出多對多關系表的字段

解決辦法:list_display 字段展示上不要加入 多對多關系的字段

8、通過接口擷取資料庫資料,某字段是多對多關系,報錯TypeError: Object of type 'ManyRelatedManager' is not JSON serializable

buglist: django-mysql 增删改查功能

解決辦法:json.loads(serializers.serialize())  轉一下資料類型即可

def getBook(request):

    if request.method == "GET":

        page = int(request.GET.get('page',''))-1

        rows = int(request.GET.get('rows',''))

        list = models.Book.objects.all().order_by("-id")

        allList = []

        for li in list:

            author_list = json.loads(serializers.serialize("json", li.author.all(), ensure_ascii=False))

            author_name = ''

            author_id = []

            for a in author_list:

                author_id.append(a['pk'])

                author_name += a['fields']['name'] + '、'

           

            allList.append({

                "id": li.id,

                "name": li.name,

                "price": li.price,

                "saleNum": li.saleNum,

                "publisher": li.publisher,

                "author_id": author_id,

                "author": author_name,

                "publish_date": json.loads(json.dumps(li.publish_date, cls=DateEncoder)),

            })

        total = len(allList)

        p = Datagrid()

        json_data_list = p.page(page, rows, total, allList)

        print (json_data_list)

        return HttpResponse(json.dumps(json_data_list), content_type='application/json; charset=utf-8')
           

9、通過接口擷取資料庫資料,某字段是一對多關系,報錯TypeError: Object of type 'Publisher' is not JSON serializable

buglist: django-mysql 增删改查功能

解決辦法:

資料原始字段:li.publisher, 但是因為是ForeignKey關聯其他表所得資料,并且預設外鍵為id

allList.append({

    "id": li.id,

    "name": li.name,

    "price": li.price,

    "saleNum": li.saleNum,

    "publisher": li.publisher_id,

    "publish_date": json.loads(json.dumps(li.publish_date, cls=DateEncoder)),

})
           
buglist: django-mysql 增删改查功能

10、多對多:TypeError: Direct assignment to the forward side of a many-to-many set is prohibited. Use author.set() instead.

buglist: django-mysql 增删改查功能

解決辦法:

1.getlist()

2.author[]

authors_list = request.POST.getlist("author[]")
           

11 、主鍵由自增改為手動:django.db.utils.InternalError: (1833, "Cannot change column 'id': used in a foreign key constraint 'proApp_author_book_book_id_b4feaab6_fk_proApp_book_id' of table 'python_sql.proapp_author_book'")

class Book(models.Model):
    id = models.FloatField(primary_key=True)
           
book = models.Book.objects.all()
if len(book) > 0:
    maxId = models.Book.objects.latest('id').id
else:
    maxId = 0
maxId += 1

dic = {
    'id': maxId,
}
b1 = models.Book(**dic)