zoukankan      html  css  js  c++  java
  • django相关字段解释(slug)

    1、slug:用于生成一个有意义(valid, meaninful)URL  参考(http://stackoverflow.com/questions/427102/what-is-a-slug-in-django)

    比如:http://stackoverflow.com/questions/427102/what-is-a-slug-in-django  后面的“what-is-a-slug-in-django”就是经过slug后的产物

    如何使用:

    需要使用slugify功能:from django.utils.text import slugify

    例子:slugify(value)  If value is "Joel is a slug", the output will be "joel-is-a-slug".

    2、SlugField:也是起到类似作用,只不过这个一般是后台直接添加时使用,比如:slug = models.SlugField(unique=True)   这样在后台就有个slug框,填写后,URL中就包含slug中的内容。

    3、pre_save:被保存进数据库前的预存储。  前面使用slug有一个问题,slug是从title中取值,但还没保存进数据库如何取?pre_save就起到这样的作用,保存开始前会发出信号,我们利用发出的信号,经过函数来进行 “准备数据”。函数(接收器)接受这个信号的方法有两个:一是connect方法,另一个是使用receiver() 装饰器来自动连接

    from django.db.models.signals import pre_save

    pre_save.connect(pre_save_post_receiver, sender=Post)

    参考:http://python.usyiyi.cn/django/topics/signals.html#receiver-functions

    http://stackoverflow.com/questions/6461989/populating-django-field-with-pre-save

    http://python.usyiyi.cn/django/topics/signals.html

    (保存时发生的事情:http://sns.hwcrazy.com/django/ref/models/instances/index.html)

    4、从url到最后的创建成功

    url.py:
      url(r'^create/$', post_create)----------匹配视图post_create
    views.py:
      from .forms import PostForm-------------关联到form
      def post_create(request):
         form = PostForm(request.POST or None, request.FILES or None)
    form.py
    from .models import Post
    class PostForm(forms.ModelForm):
        class Meta:
            model = Post -------------关联到Post类
    models.py
    pre_save.connect(pre_save_post_receiver, sender=Post) ------sender – 指定一个特定的sender,来从它那里接受信号

    最后返回slug

    5、manager:

        1、模块manager是一个对象(类),Django模块通过它进行数据库查询。 每个Django模块至少有一个manager,你可以创建自定义manager以定制数据库访问。在modles.py中,如果我们没有特别定义,默认manager(objects)将会被自动创建,即常见的这个Post.objects.all()。

        2、我们可以自定义manager以定制数据库访问

    class PostManager(models.Manager):
        def active(self, *args, **kwargs):
            return super(PostManager, self).filter(draft=False).filter(publish__lte=timezone.now())
    
    my_objects = PostManager() # 如果是objects,那就会替换默认的objects

    这样之后,我们就可以通过Post.myobjects.all()来访问过滤之后的数据了

    参考:http://www.jb51.net/article/69767.htm

    6、super:

    上边的super(PostManager, self).filter(),,中的super,它会找出PostManager所继承的类,首先找到的filter方法来进行。这里涉及到继承中的方法解析顺序(MRO)。

    MRO分两类

    经典类:从左到右的深度优先查找

    新式类:它仍然采用从左至右的深度优先遍历,但是如果遍历中出现重复的类,只保留最后一个

    参考:http://hanjianwei.com/2013/07/25/python-mro/          http://stackoverflow.com/questions/7141820/use-of-python-super-function-in-django-model

  • 相关阅读:
    Python 写一个俄罗斯方块游戏
    您能解决这3个(看似)简单的Python问题吗?
    Python selenium爬虫实现定时任务过程解析
    Python-Django-Ajax进阶2
    Python-Django-Ajax进阶
    Python 数据-入门到进阶开发之路
    Python-Numpy数组计算
    Python-Django-Ajax
    Python-web应用 +HTTP协议 +web框架
    Python-socketserver实现并发- 源码分析
  • 原文地址:https://www.cnblogs.com/ohmydenzi/p/5584846.html
Copyright © 2011-2022 走看看