美文网首页
在Win10下使用pycharm建立python3Django应

在Win10下使用pycharm建立python3Django应

作者: fancy_gogo | 来源:发表于2018-08-02 21:13 被阅读0次

    这篇文章主要记录的是在学习Django时遇到的一些问题。

    1.关于django创建数据库及表迁移

    1.数据库配置:setting中

    DATABASES = {
        'default': {
            # 'ENGINE': 'django.db.backends.sqlite3',
            # 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
            'ENGINE':'django.db.backends.mysql',
            'HOST':'127.0.0.1',
            'PORT':'3306',
            'USER':'root',
            'PASSWORD':'mysql',
            'NAME':'mysql_django'
        }
    }
    

    2.创建数据库:

    create database mysql_django charset=utf8; 
    

    3.在project同名的app下的init.py内设置:(解决django开发使用python3 无法生成迁移问题)

    (把pymysql改名为MySQLdb 否则报错: No module name MySQLdb)

    import pymysql
    pymysql.install_as_MySQLdb()
    

    ps:(在 python2 中,使用 pip install mysql-python进行安装连接MySQL的库,使用时 import MySQLdb进行使用。在 python3 中,改变了连接库,改为了 pymysql 库,使用pip install pymysql进行安装,直接导入import pymysql使用。本来在上面的基础上把 python3 的 pymysql 库安装上去就行了,但是问题依旧。经过查阅得知, Django 依旧是使用 py2 的 MySQLdb 库的,得到进行适当的转换才行)

    4.新建数据库应用:

    python manage.py startapp books_test
    

    5.在project同名的app下的setting中注册新应用(忘记注册的话数据表不能迁移成功) 否则报错: No changes detected

    6.在modles.py中定义模型类

    7.生成迁移文件:

    python manage.py makemigrations
    

    8.迁移:

    python manage.py migrate
    

    2. [Django在根据models生成数据库表时报 init() missing 1 required positional argument: 'on_delete']

    from django.db import models
    
    class BookInfoManager(models.Manager):
        def get_queryset(self):
            return super(BookInfoManager,self).get_queryset().filter(isDelete=False)
    
        def create(self,btitle,bpub_date):
            b=BookInfo()
            b.btitle=btitle
            b.bpub_date=bpub_date
            b.bread=0
            b.bcommet=0
            b.isDelete=False
            return b
    
    
    class BookInfo(models.Model):
        btitle=models.CharField(max_length=20)
        bpub_date=models.DateTimeField(db_column='pub_date')
        bread=models.IntegerField(default=0)
        bcommet=models.IntegerField(null=False)
        isDelete=models.BooleanField(default=False)
    
        class Meta:
            db_table='bookinfo'
    
    
    class HeroInfo(models.Model):
        hname=models.CharField(max_length=10)
        hgender=models.BooleanField(default=True)
        hcontent=models.CharField(max_length=1000)
        isDelete=models.BooleanField(default=False)
        book=models.ForeignKey(BookInfo)
    
    (venv) C:\Users\fanxi\Desktop\编程\Django\projects\test2>python manage.py makemigrations
    Traceback (most recent call last):
      File "manage.py", line 15, in <module>
        execute_from_command_line(sys.argv)
      File "D:\Program Files\python3_6\lib\site-packages\django\core\management\__init__.py", line 371, in execute_from_command_line
        utility.execute()
      File "D:\Program Files\python3_6\lib\site-packages\django\core\management\__init__.py", line 347, in execute
        django.setup()
      File "D:\Program Files\python3_6\lib\site-packages\django\__init__.py", line 24, in setup
        apps.populate(settings.INSTALLED_APPS)
      File "D:\Program Files\python3_6\lib\site-packages\django\apps\registry.py", line 112, in populate
        app_config.import_models()
      File "D:\Program Files\python3_6\lib\site-packages\django\apps\config.py", line 198, in import_models
        self.models_module = import_module(models_module_name)
      File "D:\Program Files\python3_6\lib\importlib\__init__.py", line 126, in import_module
        return _bootstrap._gcd_import(name[level:], package, level)
      File "<frozen importlib._bootstrap>", line 994, in _gcd_import
      File "<frozen importlib._bootstrap>", line 971, in _find_and_load
      File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
      File "<frozen importlib._bootstrap>", line 665, in _load_unlocked
      File "<frozen importlib._bootstrap_external>", line 678, in exec_module
      File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
      File "C:\Users\fanxi\Desktop\编程\Django\projects\test2\booktest\models.py", line 41, in <module>
        class HeroInfo(models.Model):
      File "C:\Users\fanxi\Desktop\编程\Django\projects\test2\booktest\models.py", line 46, in HeroInfo
        book=models.ForeignKey(BookInfo)
    TypeError: __init__() missing 1 required positional argument: 'on_delete'
    

    解决办法:herobook=models.ForeignKey('BookInfo',on_delete=models.CASCADE,)
    即在外键值的后面加上 on_delete=models.CASCADE

    原因:
    在django2.0后,定义外键和一对一关系的时候需要加on_delete选项,此参数为了避免两个表里的数据不一致问题,不然会报错:
    TypeError: init() missing 1 required positional argument: 'on_delete'
    举例说明:

    user=models.OneToOneField(User)
    owner=models.ForeignKey(UserProfile)
    

    需要改成:

    user=models.OneToOneField(User,on_delete=models.CASCADE)
    

    --在老版本这个参数(models.CASCADE)是默认值

    owner=models.ForeignKey(UserProfile,on_delete=models.CASCADE)
    

    --在老版本这个参数(models.CASCADE)是默认值
    参数说明:
    on_deleteCASCADE、PROTECT、SET_NULL、SET_DEFAULT、SET()五个可选择的值
    CASCADE:此值设置,是级联删除。
    PROTECT:此值设置,是会报完整性错误。
    SET_NULL:此值设置,会把外键设置为null,前提是允许为null。
    SET_DEFAULT:此值设置,会把设置为外键的默认值。
    SET():此值设置,会调用外面的值,可以是一个函数。
    一般情况下使用CASCADE就可以了。

    相关文章

      网友评论

          本文标题:在Win10下使用pycharm建立python3Django应

          本文链接:https://www.haomeiwen.com/subject/hyasvftx.html