Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django select where field is the concatenation of a string and column value

I'm trying to select a row where a field is the concatenation of a string and column value. This was the closest I could get:

qs = Report.objects.filter(job=self, persona__identity="u" + F("user__id"))

Report has fields persona and user. A persona object contains an identity field that is the concatenation of an identifier and an id. I'm trying to get all reports where the persona's identity string matches the user referenced by the report. (Note these are not my actual table names...everything changed to protect the innocent.)

This produces a query like,

WHERE (`persona`.`identity` =  u + `report`.`user_id` AND ...

but what I really need is something like

WHERE (`persona`.`identity` =  CONCAT("u", `report`.`user_id`) AND ...

Is there a way to do this with the ORM?

like image 980
Eric Conner Avatar asked Feb 23 '23 02:02

Eric Conner


2 Answers

You could use extra to define the lookup in raw SQL. Something like:

Report.objects.extra({
  where=['(`persona`.`identity` = CONCAT("u", `report`.`user_id`)']
})

There are some downsides to using raw SQL, such as the code not being portable across different DB engines, but for complex queries, it is far more expressive than trying to shoehorn a solution into the ORM.

like image 73
Gary Chambers Avatar answered Feb 25 '23 17:02

Gary Chambers


The alternative is available in Django 1.8:

from django.db.models import Value
from django.db.models.functions import Concat

Report.objects.filter(persona__identity=Concat(Value('u'), 'user__id'))
like image 38
andrea.ge Avatar answered Feb 25 '23 15:02

andrea.ge