Django model

多表关联查询 - 计算机的世界主要就是操作数据,所以orm一定要使用好

学习使用Django,重要的一块就orm。

初次使用感觉总体还是很好用的。主要是Django的文档比较全。

只要多看看文档,一切问题还是都能解决的。

对于初学者而言,其中最难的就是多表关联查询,以及列表或group返回关联查询的结果。

差不多用了一天的时间,粗略看了Django关于model的文档,真是大而全呀。

1:在QuerySet使用关联表的字段名字规则是

Django offers a powerful and intuitive way to “follow” relationships in lookups, taking care of the SQL JOINs for you automatically, behind the scenes. To span a relationship, just use the field name of related fields across models, separated by double underscores, until you get to the field you want.

最重要的是这种 __ 可以无限制的用很多个,这取决于你的数据库结构。

2:查到后取值得字段名字

取值就简单些,直接把字段名作为属性就可以取值了。如: entry.blog.name
一对多的关系就必须在名字后加上_set, 如 blog.entry_set.all()

3:关于一对多或多对多的关系链,查找的时候一定要理解“Spanning multi-valued relationships”这段的意思,被给自己留下查询的隐患。

详见:Django文档Spanning multi-valued relationships段落

这里就不再做叙述了。

However, unlike the behavior when using filter(), this will not limit blogs based on entries that satisfy both conditions. In order to do that, i.e. to select all blogs that do not contain entries published with “Lennon” that were published in 2008, you need to make two queries:

Blog.objects.exclude(
    entry=Entry.objects.filter(
        headline__contains='Lennon',
        pub_date__year=2008,
    ),
)

4:这里提到的功能很是好用。可以用来写把查到的数据写成字典或列表的方法, 进而把数据传到前端使用。

http://www.cnblogs.com/tuifeideyouran/p/3938515.html

或者查看文档 Model Managers — django-model-utils 2.3a1 documentation

from datetime import datetime
from django.db import models
from django.db.models.query import QuerySet
from model_utils.managers import PassThroughManager

class PostQuerySet(QuerySet):
    def by_author(self, user):
        return self.filter(user=user)

    def published(self):
        return self.filter(published__lte=datetime.now())

    def unpublished(self):
        return self.filter(published__gte=datetime.now())


class Post(models.Model):
    user = models.ForeignKey(User)
    published = models.DateTimeField()

    objects = PassThroughManager.for_queryset_class(PostQuerySet)()

Post.objects.published()
Post.objects.by_author(user=request.user).unpublished()
posted @ 2015-05-21 16:06  大大鼓  阅读(173)  评论(0)    收藏  举报