码迷,mamicode.com
首页 > 其他好文 > 详细

django orm 操作

时间:2016-06-16 16:18:23      阅读:162      评论:0      收藏:0      [点我收藏+]

标签:

django的orm使用方便,但对于一些复杂的操作,需要遵循特定的规范,特例特别记录一下:

模型:

from django.db import models

class Blog(models.Model):
    name = models.CharField(max_length=100)
    tagline = models.TextField()

    def __str__(self):              # __unicode__ on Python 2
        return self.name

class Author(models.Model):
    name = models.CharField(max_length=50)
    email = models.EmailField()

    def __str__(self):              # __unicode__ on Python 2
        return self.name

class Entry(models.Model):
    blog = models.ForeignKey(Blog)
    headline = models.CharField(max_length=255)
    body_text = models.TextField()
    pub_date = models.DateField()
    mod_date = models.DateField()
    authors = models.ManyToManyField(Author)
    n_comments = models.IntegerField()
    n_pingbacks = models.IntegerField()
    rating = models.IntegerField()

    def __str__(self):              # __unicode__ on Python 2
        return self.headline

1、Entry关联Blog

    Entry.objects.all().select_related()

   对应sql:select entry.blog, ...  from entry inner join blog on entry.id=blog.id

2、Entry按关联模型中的字段进行排序

     Entry.objects..filter(‘blog__headline‘).all().select_related()

django orm 操作

标签:

原文地址:http://www.cnblogs.com/nerrissa/p/5591293.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!