I have two tables, subscriptions and user_subscription. I wanted to be able to search from the name field in subscription for anything the user is not already subscribed to. I wrote a sql query as per below:
select e.*
from subscription e, user_subscription u
where e.id != u.sub_id and u.user_id = 7 and e.name like '%mic%'
order by name limit 0,50
My question is, is there a way to do this query using the django orm framework? I’m able to do the search of subscription table properly, problem is that when the user is already subscribed, I don’t want those results to show. The sub_id field in user_subscription is a foreign key relationship mapping to the subsciption id.
Yes – look into the Manager.raw method, which will let you run raw SQL queries. You’d want to use
Subscription.objects.raw(...)for your query.