问题
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