Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

COACHTHEM's avatar

Is there a method like toSql() to see the raw sql query with the parameters mapped automatically.

I am doing test to see whether the query binding what I have written is accurate. Currently I am using toSql() method which outputs the raw sql with ? as the value supplied to conditions.

But sometimes to make the test process faster I would have preferred to use a method that would return the sql string with values binding done automatically.

Instead of expecting select name from user where id=? I am expecting a result like this select name from user where id=2

0 likes
2 replies
shubhashishitservices's avatar

The raw() manager method can be used to perform raw SQL queries that return model instances:

Manager.raw(raw_query, params=None, translations=None)¶

This method takes a raw SQL query, executes it, and returns a django.db.models.query.RawQuerySet instance. This RawQuerySet instance can be iterated over just like a normal QuerySet to provide object instances.

This is best illustrated with an example. Suppose you have the following model:

class Person(models.Model): first_name = models.CharField(...) last_name = models.CharField(...) birth_date = models.DateField(...)

You could then execute custom SQL like so:

for p in Person.objects.raw('SELECT * FROM myapp_person'): ... print(p) John Smith Jane Jones

Try This or visit Us

Please or to participate in this conversation.