Additional column in Queryset with condition

15 views
Skip to first unread message

Saurabh Adhikary

unread,
May 23, 2020, 12:33:55 PM5/23/20
to Django users
Hello ,

I need some advice / tips.

I am in a fix.
I have 2 databases & I want to join 2 tables of that. As we know the foreign key concept with 2 separate databases is not possible. 

Basically what I want is to add a custom column to a queryset and pass the current row.name value to a function and that function will return location. The return value should be saved for each row individually. Each row will have different values. Currently, by annotate the function is calling but :
1)  name values are not getting passed
2) anything returned once is saved for the entire queryset.


Constraint - change in models is difficult for my prod environment.

database1.table1

database2.table1
namerating
outletlocation
pizza hut5
pizza-hutMumbai
mc donalds4
mc-donaldsWashington

Now, I want to get location from database2.table1 and sort it with this field .

What I have tried :
1 - queryset.annotate(loc=Value('abc', output_field=CharField())) and later updating the queryset.  But the main queryset doesn't gets updated by each row of the custom column. All the values gets updated by the same value.
2 - queryset.extra(select={'loc': myfunc('name')}) but here the column values are not getting passed.
3 - queryset.extra(select={'loc': "select 'location' from database2.table1 where outlet == %s"},select_params=('name',)) but here the column values are not getting passed.


Kindly , if you can help find a solution by :
- handling the queryset in a better way
- writing a query like Count as that is working fine for a similar column (although I know this works on Foreign key, but still if the logic is helped how to write Count type of function I can write my own snippet)


Regards,
Saurabh Adhikary

Reply all
Reply to author
Forward
0 new messages