django查询与... objects.raw [英] django query with ...objects.raw

查看:593
本文介绍了django查询与... objects.raw的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用这个
进行两个模型的查询model.objects.raw(...)

并且在sql查询中具有INNER JOIN与另一个模型(表)这是可能的

How I can make a query with two models using this model.objects.raw(...)
and into the sql query has the INNER JOIN with the another model(table) this is possible

model.objects.raw('
SELECT     establecimiento.nombre, categoria.titulo
FROM         establecimiento INNER JOIN
                      categoria ON establecimiento.categoria = categoria.id')

我需要用他的类别名称打印establecimiento的名字

I need print the establecimiento's name with his categoria's name

class Establecimiento(models.Model):
    nombre = models.CharField(max_length = 140)
    categoria = models.ForeignKey(Categoria)
    ciudad = models.ForeignKey(Ciudad)
    def __unicode__(self):
        return self.nombre



class Categoria(models.Model):
    titulo = models.CharField(max_length = 140)


推荐答案

从OR获取对象M自动执行所需的任何连接,并返回可用于跟踪关系的对象(模型的实例)。

Fetching objects from the ORM automatically does any joins required and will return objects (instances of the models) which you can use to follow relationships.

如果您只是获取所有的 Establecimiento 对象,您可以访问相关的 Categoria 对象,如下所示:

If you simply fetch all your Establecimiento objects, you can access the related Categoria objects, like this:

all_objects = Establecimiento.objects.all()

for obj in all_objects:
   print('Number: {} Category: {}'.format(obj.nombre, obj.categoria.titulo))

或者,如果要获取这两个特定属性,请使用 ,如下所示:

Or, if you want to fetch only those two specific properties, use values, like this:

all_objects = Establecimiento.objects.values('nombre','ciudad__titulo')
for obj in all_objects:
   print('Number: {} Category: {}'.fromat(obj['nombre'],obj['ciudad__titulo']))

这篇关于django查询与... objects.raw的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆