mysqldjango

Use queryset result as a parameter to a raw SQL in Django


I have a queryset result that I need to retrieve, lets call it QSA, and also another queryset which is obtained by Raw SQL, lets call this one QSB, but for the raw sql(QSB) I need only a field of QSA as a parameter, only one, but I don't want to make another query only just for that parameter.

I tried to send this as a parameter to QSB: QSA.values('pk') but it doesn't work, I obtained an empty result, and I tried to run the SQL query on Workbench and it works (I'm using MySQL), so I think the problem is in the way that I send the parameter.


Solution

  • I figured out how to make it work. I tried %s and %(key)s placeholders, and none of them worked with QSA.values('pk') as parameter, but later %s worked with QSA.values_list('pk',flat=True) and that's it, thats the way a queryset result can be send as parameter for a raw sql query in Django.