测试用例 写入数据库是汉字 查询数据时变为问号 数据库已设置utf-8格式

来源:7-14 模型类和视图的测试用例

慕容7472185

2021-03-02

编写测试用例时,存入数据库的数据是汉字,查询数据时汉字变成了问号,数据库也是utf8格式,而且在view视图中查询出的结果均是汉字。
图片描述
其他语句都顺利通过,唯独

assert Article.objects.get_published()[0].title == "第一篇文章"

这句代码执行失败,原因是查询数据时汉字变为了问号。

Article.objects.get_published()[0].title

这句同样的代码,在view视图函数中查询出的结果显示是中文汉字,
试了好多方法最终汉字都是显示问号。
麻烦老师给讲解下,谢谢。

写回答

1回答

Jack

2021-03-02

您好,函数是这样的

@python_2_unicode_compatible
class ArticleQuerySet(models.query.QuerySet):
   """自定义QuerySet,提高模型类的可用性"""

   def get_published(self):
       """返回已发表的文章"""
       return self.filter(status="P").select_related('user')

my.cnf文件是这样的,默认设置

[zanhu@zanhu ~]$ cat /etc/my.cnf

# For advice on how to change settings please see

# http://dev.mysql.com/doc/refman/8.0/en/server-configuration-defaults.html


[mysqld]

# Remove leading # and set to the amount of RAM for the most important data

# cache in MySQL. Start at 70% of total RAM for dedicated server, else 10%.

# innodb_buffer_pool_size = 128M

#

# Remove the leading "# " to disable binary logging

# Binary logging captures changes between backups and is enabled by

# default. It's default setting is log_bin=binlog

# disable_log_bin

#

# Remove leading # to set options mainly useful for reporting servers.

# The server defaults are faster for transactions and fast SELECTs.

# Adjust sizes as needed, experiment to find the optimal values.

# join_buffer_size = 128M

# sort_buffer_size = 2M

# read_rnd_buffer_size = 2M

#

# Remove leading # to revert to previous value for default_authentication_plugin,

# this will increase compatibility with older clients. For background, see:

# https://dev.mysql.com/doc/refman/8.0/en/server-system-variables.html#sysvar_default_authentication_plugin

# default-authentication-plugin=mysql_native_password

datadir=/var/lib/mysql

socket=/var/lib/mysql/mysql.sock

log-error=/var/log/mysqld.log

pid-file=/var/run/mysqld/mysqld.pid

创建数据库的时候是 CREATE DATABASE zanhu charset utf8;

0
2
慕容7472185
非常感谢!
2021-03-03
共2条回复

Django高级实战 开发企业级问答网站

融合Django高级用法/算法/设计模式/TestCase测试/云计算打造项目

900 学习 · 756 问题

查看课程