django orm 操作

时间:2022-06-05 16:33:56

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()
3、执行原始的sql

Entry.objects.raw(sql) 
     参考:https://docs.djangoproject.com/en/1.10/topics/db/sql/
4、