如何使用django orm编写带有额外数据的原始sql?

时间:2016-05-19 15:03:28

标签: django django-queryset

我想使用django orm编写以下查询。 机型:

class Blog(models.Model):
    author = models.CharField(max_length=200)
    text = models.TextField()

class BlogImage(models.Model):
    blog = models.ForeignKey('Blog')
    image_url = models.CharField()
    principal = models.BooleanField()

查询将是

select * ,
   (
     select image_url 
     from blog_image bi 
     where bi.blog_id = b.id 
        and bi.principal=1
   ) as blog_main_image
from blog b

任何想法,如何使用queryset编写它?

3 个答案:

答案 0 :(得分:0)

你可以使用djangos raw函数。 https://docs.djangoproject.com/en/1.9/topics/db/sql/

答案 1 :(得分:0)

Blog.objects.all().extra("select={'blog_main_image': "select image_url 
     from blog_image 
     where blog_id = blog.id 
        and principal=1}")

或者只是循环浏览博客并获取图片

blogs = Blog.objects.all()
for blog in blogs:
    if blog.blogimage_set.filter(principal=1).exists():
        main_image = blog.blogimage_set.filter(principal=1)[0]
    else:
        main_image = None

答案 2 :(得分:0)

在google上找到django用户组的答案:

from django.db.models import Prefetch

Blog.objects.all().prefetch_related(
    Prefetch('image', 
             queryset=BlogImage.objects.filter(principal=1), 
             to_attr='blog_main_image'
            )
)