i have two tables and need to write this query in django
my models are:
class students(models.Model):
name = models.CharField(max_length=30)
active = models.BooleanField(max_length=1)
class college(models.Model):
department = models.CharField(max_length=20)
college_name = models.CharField(max_length = 50)
s_id = models.ForeignKey(students, on_delete=models.CASCADE)
my mysql query:
select b.name,a.department from college as a
inner join students as b on (a.s_id = b.id)
where (a.department = 'CSE' AND b.active = 1)
i just want to write this query in django
college.objects.filter(department='CSE',s_id__active=True).values('s_id__name','department')
use this
Related
I am trying to convert sql code to django orm code.
I don't want to use python raw function
SELECT
u.`user_id` as 'dp_id',
cp.`email` as 'dp_email',
cp.`name` as 'dp_name',
u2.`user_id` as 'cm_id',
cp2.`email` as 'cm_email',
cp2.`name` as 'cm_name'
FROM `user` u
INNER JOIN customer_profile cp
ON u.`customer_profile_id` = cp.`id`
INNER JOIN branch_user bm
ON bm.`child_user_id` = u.`user_id`
AND bm.`parent_role_id` = 14
AND bm.`is_deleted` = 0
INNER JOIN user u2
ON u2.`user_id` = bm.`parent_user_id`
AND u2.`is_deleted` = 0
INNER JOIN customer_profile cp2
ON u2.`customer_profile_id` = cp2.`id`
WHERE u.`user_id` = ?
AND u.`is_deleted` = 0
I did something like this :
cp_emails = User.objects.filter(branch_user_childUser__parent_role_id=14, branch_user_childUser__is_deleted=0).select_related('customer_profile').prefetch_related('branch_user_childUser')
But i am not able to add user u2 to django orm as it's same user table and that too compare with "bm" i.e this line "ON u2.user_id = bm.parent_user_id"
My models:
class User(models.Model):
user_id = models.AutoField(primary_key=True)
customer_profile = models.ForeignKey(
'login.CustomerProfile', on_delete=models.CASCADE, default=None
)
class BackboneUserManagerMapping(models.Model):
child_user = models.ForeignKey('login.User', related_name='branch_user_childUser', on_delete=models.DO_NOTHING)
parent_user = models.ForeignKey('login.User', related_name='branch_user_childUser', on_delete=models.DO_NOTHING)
parent_role_id = models.IntegerField()
is_deleted = models.BooleanField(default=False)
class CustomerProfile(AbstractBaseUser, PermissionsMixin):
id = models.AutoField(primary_key=True)
email = models.EmailField(default=None, unique=True)
mobile = models.CharField(max_length=13, default=None)
alt_mobile = models.CharField(max_length=13, null=True)
name = models.CharField(max_length=255, default=None)
Models:
Items(models.Model):
name = models.CharField(max_length=250, verbose_name="Item Name")
created_date = models.DateTimeField(auto_now_add=True)
Accounts(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
url_tag = models.CharField(max_length=200)
item = models.ForeignKey(Items, on_delete=models.CASCADE)
Comments(models.Model):
item = models.ForeignKey(Items, on_delete=models.CASCADE, null=True)
comment = models.TextField(null=True)
url_tag = models.URLField(null=True)
is_flagged = models.BooleanField(default=False, null=True)
response_required = models.BooleanField(default=True)
created_date = models.DateTimeField(auto_now_add=True)
Responses(models.Model):
response = models.TextField()
comment = models.ForeignKey(Comments, on_delete=models.CASCADE)
created_date = models.DateTimeField(auto_now_add=True)
Sql Query:
select c.id as comment_id, c.created_date, c.is_flagged, c.response_required
from comments as c
left join responses as r on c.id = r.comment_id
inner join items as i on i.id = c.item_id and r.comment_id is null
left join accounts as a on
(a.item_id = c.item_id and lower(a.url_tag) = lower(c.url_tag)
where c.id in (12, 32, 42, 54)
ORDER BY c.created_date desc, comment_id desc;
What I tried:
filters = {
'id__in': [12, 32, 42, 54]
}
comment_objs = Comment.objects.filter(**filters)
.select_related('commentsresponses', 'item')
.order_by('-created_date', '-id')
I want to get list of comment objects after joining and applying filters.
Maybe we can use serializers here i don't know since I don't have much experience with django
If time complexity doesn't matter for you, You can use raw SQL query:
from django.db import connection
cursor = connection.cursor()
cursor.execute('''select c.id as comment_id, c.created_date, c.is_flagged,
c.response_required
from comments....''')
I have the following models
models
class User(models.Model):
ur_id = models.AutoField(primary_key=True)
ur_mailid = models.CharField(max_length=100)
...
class User_info(models.Model):
ui_id = models.AutoField(primary_key=True)
# ui_iduser = models.IntegerField()
ui_iduser = models.ForeignKey(User, on_delete=models.CASCADE)
ui_firstname = models.CharField(max_length=45)
ui_lastname = models.CharField(max_length=45)
...
class User_group(models.Model):
ug_id = models.AutoField(primary_key=True)
ug_groupname = models.CharField(max_length=100)
...
class User_groupmember(models.Model):
# ug_groupid = models.IntegerField()
# ug_userid = models.IntegerField()
ug_groupid = models.ForeignKey(User_group, on_delete=models.CASCADE)
ug_userid = models.ForeignKey(User, on_delete=models.CASCADE)
...
Here is SQL Query:
select
a.ur_id ur_id,
c.ug_id ug_id,
d.ui_mailid ui_mailid,
d.ui_firstname ui_firstname,
d.ui_lastname ui_lastname
from user a
LEFT OUTER JOIN
user_groupmember b ON a.ur_id = b.ug_userid
LEFT OUTER JOIN
user_group c ON c.ug_id = b.ug_userid
LEFT OUTER JOIN
user_info d ON d.ui_id = a.ur_id
where a.ur_mailid = 'test#test.com'
I need to convert it in ORM Query.
Is there any way to achieve it without using raw SQL?
Any help is appreciated
I got problem in making Queries. In the shell I all the time faced 'user' has no split error. and want to know how to make query about those models.
select i.id, i.name, i.email, i.memo, g.id, g.name, i.birthday, i.regdt, n.number, t.name, t.id
from webcontact_info as i
inner join webcontact_number as n on i.id = n.info_id
inner join webcontact_group as g on i.group_id = g.id
inner join webcontact_type as t on n.type_id = t.id;
this query in mysql. how can i change into query for Django?
please help me about this.
those are models.py
class Group(models.Model):
name = models.CharField(max_length=20)
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
class Type(models.Model) :
name = models.CharField(max_length=20)
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
class Info(models.Model):
name = models.CharField(max_length=20)
email = models.EmailField(null=True, blank=True, unique=True)
memo = models.CharField(max_length=200, null=True)
birthday = models.CharField(max_length=12,null=True, blank=True)
group = models.ForeignKey(Group, on_delete=models.CASCADE)
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
regdt = models.DateTimeField(auto_now_add=True)
updatedt = models.DateTimeField(auto_now_add=True)
class Number(models.Model):
number = models.CharField(max_length=11)
info = models.ForeignKey(Info, on_delete=models.CASCADE)
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
type = models.ForeignKey(Type, on_delete=models.CASCADE)
regdt = models.DateTimeField(auto_now_add=True)
updatedt = models.DateTimeField(auto_now_add=True)
You can just use your related object with your object. But maybe you're looking for select_related.
It will return selecting additional related-object data - It will boost query performance bit much.
infos = Info.objects.select_related('user', 'group', 'user__number').
Check more detail in django docs
I need some help with this SQL Query. It is designed to retrieve names of students with the same S.S_level values as Jaci Walker, and have taken courses (CS.C_SE_id) with Jaci Walker in the BG building.
I am having trouble on line 7. I need to be able to ensure that the people have enrolled in the same course as Jaci Walker. I'm not sure about what to put in the WHERE statement for that section.
The database schema can be seen here:
SELECT S.S_Fname, S.S_LName
FROM Student S, Enrollment E, CourseSection CS, Location L
WHERE S.S_id = E.S_id
AND E.C_SE_ID = CS.C_SE_id
AND L.Loc_id = CS.Loc_ID
AND S.S_Level = (SELECT S.S_Level FROM Student S WHERE S.S_Fname = "Jaci" AND S.S_Lname = "Walker")
AND CS.C_SE_id = (SELECT CS.C_SE_id FROM CourseSection CS WHERE **?**)
AND L.Loc_id = (SELECT L.Blodg_code FROM Location L WHERE L.Blodg_code = "BG");
I would start by using current SQL-syntax using JOIN conditions instead of using the WHERE clause to show relationships between tables. This way, you get all your table associations done and can better visually confirm you have those elements configured... THEN, tack on the criteria you are looking for.
What I have done here is to just have a PreQuery (result alias "JaciClassesInBG" ) that gets all of Jaci's classes that were enrolled in and ONLY those for the building "BG" (which was added to the JOIN clause to the location table). The WHERE clause was only for Jaci.
From that result, I have a list of all classes that Jaci took. I grabbed her ID, S_Level and C_SE_ID entries.
From that, just join back to the enrollment table of all other students based explicitly on the C_SE_ID that Jaci took (thus all students in that exact same class). However, I've EXCLUDED (via AND NOT...) Jaci's student ID from the list... we know she took the class, we are looking for everyone ELSE.
Finally, join that result back to the students table based on the common enrollment. Now, we can associate the common "S_LEVEL" criteria of Jaci to those students...
Now, you can get whatever details you want for display... in this case, I am grabbing each student, and what class they had in common with Jaci. One student may have been in multiple classes. This will show each. If you only care about one instance, I would just change the top to...
select DISTINCT S2.S_FName, S2.S_LName...
SELECT
JaciClassesInBG.Course_Code,
JaciClassesInBG.Course_Name,
S2.S_FName,
S2.S_LName
from
( SELECT
S.ID,
S.S_Level,
CS.C_SE_ID,
C.Course_Code,
C.Course_Name
FROM
Student S
JOIN Enrollment E
ON S.S_id = E.S_id
JOIN CourseSection CS
ON E.C_SE_ID = CS.C_SE_id
JOIN Location L
ON L.Loc_id = CS.Loc_ID
AND L.Blodg_Code = "BG"
JOIN Course C
ON CS.Course_ID = C.Course_ID
WHERE
S.S_Fname = "Jaci"
AND S.S_Lname = "Walker" ) JaciClassesInBG
JOIN
Enrollment E2
ON JaciClassesInBG.C_SE_ID = E2.C_SE_ID
AND NOT JaciClassesInBG.S_ID = E2.S_ID
JOIN Students S2
ON E2.S_ID = S2.S_ID
AND JaciClassesInBG.S_Level = S2.S_Level
IF I'm understanding the question right this should work:
SELECT s.S_Fname, s.S_LName
FROM Student s
INNER JOIN Enrollment e ON s.S_id = e.S_id
INNER JOIN CourseSection cs ON e.C_SE_ID = cs.C_SE_id
INNER JOIN Location l ON cs.Loc_ID = l.Loc_id
INNER JOIN Student s2 ON s.S_Level = s2.S_Level AND s2.S_Fname = "Jaci" AND s2.S_Lname = "Walker"
INNER JOIN Enrollment e2 ON s2.S_id = e2.S_id
INNER JOIN CourseSection cs2 ON e2.C_SE_ID = cs2.C_SE_id
WHERE l.Loc_id = l.Blodg_code = "BG"
AND cs.Course_ID = cs2.Course_ID
I'm unable to test at the moment and it was quickly done. Maybe a better solution can be found?
Without access to the data I can't test but the following may help (the first inner select is pulling back all the relevant C_SE_ID's)
SELECT S.S_Fname, S.S_Lname
FROM Student S, Enrollment E
WHERE S.S_id = E.S_id
AND E.C_SE_ID IN (SELECT CS.C_SE_ID
FROM Student S2, Enrollment E2, CourseSection CS, Location L
WHERE S2.S_id = E2.S_id
AND E2.C_SE_ID = CS.C_SE_ID
AND CS.Loc_id = L.Loc_id
AND L.Blodg_code = 'BG'
AND S2.S_Fname = 'Jaci'
AND S2.S_Lname = 'Walker')
AND S.S_Level = (SELECT S3.S_Level
FROM Student S3
WHERE S3.S_Fname = 'Jaci'
AND S3.S_Lname = 'Walker')
AND S.S_Fname <> 'Jaci'
AND S.S_Lname <> 'Walker'
I would recommend using different aliases within inner queries (e.g. S2, E2) to avoid confusion.