Get multiple columns data from extra query in Django
I have two models as below:
class Model1(models.model):
id = models.UUIDField(default=uuid.uuid4, primary_key=True)
filename = models.CharField(max_length=255)
class Model2(models.model):
id = models.UUIDField(default=uuid.uuid4, primary_key=True)
filename = models.CharField(max_length=255)
I would like to get the related model2
which have the same column value in filename
as that of model1
.
My solution was to use either Subquery
or Extra
. The problem with Subquery
is that it allows only one column to be queried but what I want is a dict object of all the columns of model2
related to model1
. They do not have a foreignkey
relation to use select_related
. So I tried to use extra
but again I am getting the multiple columns error. How can I solve this problem?
My code is as below:
model1_objs = Model1.objects.filter(id=given_id).extra(
select={
"model2_obj": f"SELECT *
FROM model2
WHERE filename = model1.filename
AND id = '{model2_id}'"
}
)
This does not work.
This might not be as efficient as the solution you were thinking of but you could try this:
model1_obj = Model1.objects.get(id=given_id)
model2_objs = Model2.objects.filter(filename=model1_obj.filename)
Note: consider using the get() method to fetch unique objects
Have a look at this: Making queries (Django documentation)