I am currently wanting to run a SQL statement that will filter my database but it accesses multiple tables. From the other examples I have read on this website, they all use foreign keys not on the primary key; however, that is my current setup. I am having two issues, the first being the SQL filter. These are my models:
class UserProfile(models.Model):
user = models.ForeignKey(User, unique=True);
isATutor = models.BooleanField();
timeAvailable = models.CharField(max_length=3);
class TutorProfile(models.Model):
user = models.ForeignKey(User);
language = models.CharField(max_length=30);
unique_together = (("user", "language"), );
class Tutor(models.Model):
user = models.ForeignKey(User);
subject = models.CharField(max_length=30);
unique_together = (("user", "subject"), );
I am using raw SQL at the moment.
def sqlQuery(avail, lang, sub):
from django.db import connection, transaction
cursor = connection.cursor();
cursor.execute("SELECT a.first_name, a.last_name, a.email FROM auth_user a, books_tutor b, books_tutorprofile c, books_userprofile d WHERE a.id = b.user_id AND a.id = c.user_id AND a.id = d.user_id AND b.subject=%s AND c.language=%s AND d.timeAvailable=%s", [sub, lang, avail]);
row = cursor.fetchall();
return row;
timeAvailable is taking a three character string is in the form 'MAE' where M = morning, A=Afternoon, E=Evening and if they are not needed, we'll replace with - e.g. 'M--' is only available in morning.
So the first issue is I'd love to be able to keep the above SQL as a django model. The second issue is I need a good way to query for MAE. I'm thinking I may have to do 8 different SQL parts and UNION them depending on what is chosen.
Thanks,
Steve