• 使用pycharm开发web——django2.1.5(三)创建models并进入交互界面shell做一些简单操作


    这里model可以认为是数据对象本身

    相当于在写java代码时候model目录下创建的实体类,models.py 中可以包含多个实体类,感觉这个操作挺骚的

    下面是polls app里面的models,仍然根据刘江老师的网站进行学习,此处不赘述。

    models.py

    from django.db import models
    
    # Create your models here.
    from django.db import models
    class Question(models.Model):
        question_text = models.CharField(max_length=200)
        pub_date = models.DateTimeField('date published')
    
    class Choice(models.Model):
        question = models.ForeignKey(Question,on_delete=models.CASCADE)
        choice_text = models.CharField(max_length=200)
        votes = models.IntegerField(default=0)

    这里的Question 和 Choice 两个类,将来在mysql之中就是两张表,就叫这俩名字!而类中的属性就是字段名即column名

    完事之后,请将polls加在settings.py中的INSTALLED_APP列表中,准备迁移。

    直接用简写方式就行:

    下面在settings.py中

    # pysite/settings.py
    
    INSTALLED_APPS = [
    'polls',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    ]

    好的开始迁移,之前做的迁移是对项目整体迁移,当model有所更新的时候,新的内容需要再次同步

    终端运行:

    python manage.py makemigrations polls

    这时候得到如下提示:

    Migrations for 'polls':
      polls/migrations/0001_initial.py:
        - Create model Choice
        - Create model Question

    django获得了迁移信息,然后迁移:

    python manage.py migrate

    看到这样的画面:

    python manage.py migrate
    Operations to perform:
        Apply all migrations: admin, auth, contenttypes, polls, sessions
    Running migrations:
        Rendering model states... DONE
        Applying polls.0001_initial... OK

    这样来到数据库后,你就发现多了些东西

    两张表后缀名是不是似曾相识呢?

    没错就是想的那样。

    接下来打开进入交互界面中(在终端中):

    import django
    django.setup()

    接下来这段直接拿刘老师写的内容加一些自己的理解粘过来:

     >>> from polls.models import Question, Choice # 导入我们写的模型类
        # 现在系统内还没有questions对象
        >>> Question.objects.all()
        <QuerySet []>
    
        # 创建一个新的question对象
        # Django推荐使用timezone.now()代替python内置的datetime.datetime.now()
        # 这个timezone就来自于Django的依赖库pytz
        from django.utils import timezone
        >>> q = Question(question_text="What's new?", pub_date=timezone.now())
    
        # 你必须显式的调用save()方法,才能将对象保存到数据库内
        >>> q.save()
    
        # 默认情况,你会自动获得一个自增的名为id的主键
        >>> q.id
        1
    
        # 通过python的属性调用方式,访问模型字段的值
        >>> q.question_text
        "What's new?"
        >>> q.pub_date
        datetime.datetime(2012, 2, 26, 13, 0, 0, 775217, tzinfo=<UTC>)
    
        # 通过修改属性来修改字段的值,然后显式的调用save方法进行保存。
      #这里请注意,这种写法实际上是不安全的,因为你不会允许其他人随意更改一个类的属性值,后续应该在models里面将实体类的属性私有化而不是直接这样放,使用get,set方法获取和修改
    >>> q.question_text = "What's up?" >>> q.save() # objects.all() 用于查询数据库内的所有questions >>> Question.objects.all() <QuerySet [<Question: Question object>]>

    当调用了q.save()之后,来到你的数据库中,这里q是一个Question对象,对应的表polls_question中你会发现表里面多了一条数据,就是你刚才写的。

    django在创建表之初会自动创建id主键自增列,所以调用增删改查就不用过多考虑,你默认它(id)存在即可。

    对models进行小修改:

    models.py

    from django.db import models
    import datetime
    from django.utils import timezone
    
    # Create your models here.
    from django.db import models
    class Question(models.Model):
        question_text = models.CharField(max_length=200)
        pub_date = models.DateTimeField('date published')
        #toString()方法
        def __str__(self):
            return self.question_text
    
        def was_published_recently(self):
            return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
    
    class Choice(models.Model):
        question = models.ForeignKey(Question,on_delete=models.CASCADE)
        choice_text = models.CharField(max_length=200)
        votes = models.IntegerField(default=0)
    
        def __str__(self):
            return self.choice_text

    然后你重启shell,这时候

    >>> import django
    >>> django.setup()
    >>> from polls.models import Question, Choice
    >>> Question.objects.all()
    <QuerySet [<Question: what's up>]>

    ,今天上课先写这些喽,继续学习新知识!!

    于是我又回来了

    使用其它api

     
    Question.objects.filter(question_text__startswith='What')

    这里是区分大小写的,What !=what

     
    (venv) D:pysite>python manage.py shell
     Python 3.6.2 (v3.6.2:5fd33b5, Jul  8 2017, 04:57:36) [MSC v.1900 64 bit (AMD64)] on win32
     Type "help", "copyright", "credits" or "license" for more information.
     (InteractiveConsole)
     >>>
     >>>
     >>> from polls.models import Question, Choice
     >>> Question.objects.all()
     <QuerySet [<Question: what's up>]>
     >>> Question.objects.filter(id=1)
     <QuerySet [<Question: what's up>]>
     >>> Question.objects.filter(question_text__startswith='What')
     <QuerySet []>
     >>> Question.objects.filter(question_text__startswith='What')
     <QuerySet []>
     >>> Question.objects.filter(question_text__startswith="What's")
     <QuerySet []>
     >>> Question.objects.filter(question_text__startswith='what')
     <QuerySet [<Question: what's up>]>
     >>>  from django.utils import timezone
       File "<console>", line 1
         from django.utils import timezone
         ^
     IndentationError: unexpected indent
     >>> from django.utils import timezone
     >>> current_year = timezone.now().year
     >>> Question.objects.get(pub_date__year=current_year)
     <Question: what's up>
     >>> Question.objects.get(id=2)
     Traceback (most recent call last):
       File "<console>", line 1, in <module>
       File "D:pysitemysitevenvlibsite-packagesdjangodbmodelsmanager.py", line 82, in manager_metho
     d
         return getattr(self.get_queryset(), name)(*args, **kwargs)
       File "D:pysitemysitevenvlibsite-packagesdjangodbmodelsquery.py", line 408, in get
         self.model._meta.object_name
     polls.models.Question.DoesNotExist: Question matching query does not exist.
     >>> Question.objects.get(pk=1)
     <Question: what's up>
     >>> q = Question.objects.get(pk=1)
     >>> q.was_published_recently()
     True
     >>> q.choice_set.all()
     <QuerySet []>
     >>> q.choice_set.create(choice_text='Not much',votes=0)
     <Choice: Not much>
     >>> q.choice_set.create(choice_text='The sky',votes=0)
     <Choice: The sky>
     >>> c =  q.choice_set.create(choice_text='Just hacking again',votes=0)
     >>> c.question
     <Question: what's up>
     >>> q.choice_set.all()
     <QuerySet [<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]>
     >>> q.choice_count()
     Traceback (most recent call last):
       File "<console>", line 1, in <module>
     AttributeError: 'Question' object has no attribute 'choice_count'
     >>> q.choice_set.count()
     3
     >>> Choice.objects.filter(question__pub_date__year=current_year)
     <QuerySet [<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]>
     >>> c = q.choice_set.filter(choice_text__startwith'Just hacking')
       File "<console>", line 1
         c = q.choice_set.filter(choice_text__startwith'Just hacking')
                                                                    ^
     SyntaxError: invalid syntax
     >>> c = q.choice_set.filter(choice_text__startwith='Just hacking')
     Traceback (most recent call last):
       File "<console>", line 1, in <module>
       File "D:pysitemysitevenvlibsite-packagesdjangodbmodelsmanager.py", line 82, in manager_metho
     d
         return getattr(self.get_queryset(), name)(*args, **kwargs)
       File "D:pysitemysitevenvlibsite-packagesdjangodbmodelsquery.py", line 892, in filter
         return self._filter_or_exclude(False, *args, **kwargs)
       File "D:pysitemysitevenvlibsite-packagesdjangodbmodelsquery.py", line 910, in _filter_or_exc
     lude
         clone.query.add_q(Q(*args, **kwargs)) 
      File "D:pysitemysitevenvlibsite-packagesdjangodbmodelssqlquery.py", line 1290, in add_q 
        clause, _ = self._add_q(q_object, self.used_aliases) 
      File "D:pysitemysitevenvlibsite-packagesdjangodbmodelssqlquery.py", line 1318, in _add_q 
        split_subq=split_subq, simple_col=simple_col, 
      File "D:pysitemysitevenvlibsite-packagesdjangodbmodelssqlquery.py", line 1251, in build_fil 
    ter 
        condition = self.build_lookup(lookups, col, value) 
      File "D:pysitemysitevenvlibsite-packagesdjangodbmodelssqlquery.py", line 1110, in build_loo 
    kup 
        lhs = self.try_transform(lhs, lookup_name) 
      File "D:pysitemysitevenvlibsite-packagesdjangodbmodelssqlquery.py", line 1151, in try_trans 
    form 
        "permitted%s" % (name, output_field.__name__, suggestion) 
    django.core.exceptions.FieldError: Unsupported lookup 'startwith' for CharField or join on the field no 
    t permitted, perhaps you meant startswith or istartswith? 
    >>> c = q.choice_set.filter(choice_text__startswith='Just hacking') 
    >>> c.delete() 
    (1, {'polls.Choice': 1}) 
    >>> c.objects.all() 
    Traceback (most recent call last): 
      File "<console>", line 1, in <module> 
    AttributeError: 'QuerySet' object has no attribute 'objects' 
    >>> c.all() 
    <QuerySet []> 
    >>> q.choice_set.all() 
    <QuerySet [<Choice: Not much>, <Choice: The sky>]>
     创建超级用户,就管理员
    (venv) D:pysite>python manage.py createsuperuser
    Username (leave blank to use 'lisk'): admin
    Email address: lsk@admin.com
    Password:
    Password (again):
    Superuser created successfully.

     

    新的pysite/urls.py

     
    """pysite URL Configuration
     ​
     The `urlpatterns` list routes URLs to views. For more information please see:
         https://docs.djangoproject.com/en/2.2/topics/http/urls/
     Examples:
     Function views
         1. Add an import:  from my_app import views
         2. Add a URL to urlpatterns:  path('', views.home, name='home')
     Class-based views
         1. Add an import:  from other_app.views import Home
         2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
     Including another URLconf
         1. Import the include() function: from django.urls import include, path
         2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
     """
     from django.contrib import admin
     from django.urls import path,include
     ​
     urlpatterns = [
         path('polls/', include('polls.urls')),
         #为了安全起见将admin页面地址改为control/
         path('control/', admin.site.urls),
     ]

     启动服务,然后去127.0.0.1:8000/control/

    就可以看到登陆页面

    然后在admin.py中注册polls应用

     
    from django.contrib import admin
    from .models import Question
     ​
    admin.site.register(Question)

    之后说就是这样的效果

    这里的history可以查看操作历史

     

  • 相关阅读:
    C++输入输出缓冲区的刷新问题
    C++11中新特性之:initializer_list详解
    GCC --verbose选项, -lpthread 和-pthread的区别
    C语言的可变参数
    YCM的安装与配置
    【机器学习】正则化的线性回归 —— 岭回归与Lasso回归
    一文读懂线性回归、岭回归和Lasso回归
    美团酒旅数据治理实践
    kettle完成一个数据库到另一个数据的整体迁移
    kettle完成一个数据库到另一个数据的整体迁移
  • 原文地址:https://www.cnblogs.com/lovely-lisk/p/11037911.html
Copyright © 2020-2023  润新知