django orm 操作
Posted 妞溜溜
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了django orm 操作相关的知识,希望对你有一定的参考价值。
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 操作的主要内容,如果未能解决你的问题,请参考以下文章