django query with …objects.raw

感情迁移 提交于 2019-12-14 03:16:57

问题


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')

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)

回答1:


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.

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']))


来源:https://stackoverflow.com/questions/21359710/django-query-with-objects-raw

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!