I want to get result with ORM of Django. But I cannot get result with ORM.
I just tried with 'select_related("field_name")'. but doesn't work..
Actually, I don't know using ORM well haha...
and..
This Query is my needs
SELECT sol.idx, sol.sol_name, sol.sol_warning, sol.user_num_id, sol.auto_run_server, ur.user_ip,
pc.cpu_usage, pc.mem_usage, pc.disk_usage FROM solution AS sol
INNER JOIN ems.user AS ur ON sol.user_num_id = ur.user_num INNER JOIN pc_status AS pc ON sol.user_num_id = pc.user_num_id;
result row is ...
idx, sol_name, sol_warning, user_num_id, auto_run_server, user_ip, cpu_usage, mem_usage, disk_usage
so..
I used code is " Solution.objects.select_related('user_num') "
But I cannot get same result.
here are my python codes.
models.py
class User(models.Model):
user_num = models.IntegerField(primary_key=True, auto_created=True)
user_ip = models.CharField(max_length=20)
user_name = models.CharField(max_length=10)
user_pwd = models.CharField(max_length=10)
class Meta:
db_table = 'user'
class Solution(models.Model):
idx = models.IntegerField(primary_key=True, auto_created=True)
sol_name = models.CharField(max_length=50)
sol_warning = models.IntegerField()
user_num = models.ForeignKey(User, on_delete=models.CASCADE)
auto_run_server = models.IntegerField()
class Meta:
db_table = 'solution'
class PcStatus(models.Model):
pc_idx = models.IntegerField(primary_key=True, auto_created=True)
cpu_usage = models.IntegerField(default=0)
mem_usage = models.IntegerField(default=0)
disk_usage = models.IntegerField(default=0)
user_num = models.ForeignKey(User, on_delete=models.CASCADE)
class Meta:
db_table = 'pc_status'
Related
I have the following models:
class SystemTable(models.Model):
id = models.FloatField(primary_key=True)
system_name = models.CharField(max_length=50)
system_desc = models.CharField(max_length=200, blank=True, null=True)
system_url = models.CharField(max_length=2000, blank=True, null=True)
status = models.ForeignKey(StatusLkp, models.DO_NOTHING, db_column='status',default=1)
date_created = models.DateTimeField(default=datetime.now())
objects = models.Manager()
class Meta:
app_label = 'system_table'
managed = True
db_table = 'system_table'
class SystemPagesTable(models.Model):
id = models.FloatField(primary_key=True)
system = models.ForeignKey(SystemTable, on_delete=models.CASCADE)
page_name = models.CharField(max_length=200)
page_link_xpath = models.CharField(max_length=2000)
flag = models.FloatField(blank=True, null=True)
status = models.ForeignKey(StatusLkp, models.DO_NOTHING, db_column='status',default=1)
date_created = models.DateTimeField(default=datetime.now())
objects = models.Manager()
class Meta:
app_label = 'system_pages_table'
managed = True
db_table = 'system_pages_table'
I want to perform the following SQL query:
select
s.*,
(select count(*) from page p where p.system_id = s.id) as NUM_OF_PAGES
from system s;
How do I perform the above query with Django's ORM without having to use a for loop?
I do not want a result based on one system, I want to retrieve all systems with their page counts.
Try to use annotate:
from django.db.models import Count
System.objects.annotate(num_pages=Count('page'))
I want to store thousands of records in the Student table which has id_users foreign key field. I tried without having foreign key it works smooth but when I added fk constraint it becomes very very slow and took more than 20mins to store 500 records and same without fk took only few seconds.
models - Below models are from different apps
./users/models.py
class Users(models.Model):
id = models.IntegerField(primary_key=True)
cts = models.DateTimeField(blank=True, null=True)
uts = models.DateTimeField(blank=True, null=True)
id_states = models.ForeignKey(States, models.DO_NOTHING, db_column='id_states', blank=True, null=True)
id_user_type = models.ForeignKey(UserType, models.DO_NOTHING, db_column='id_user_type')
firstname = models.TextField(blank=True, null=True)
lastname = models.TextField(blank=True, null=True)
class Meta:
managed = False
db_table = 'users'
./student/models.py
class Student(models.Model):
id = models.BigAutoField(primary_key=True)
cts = models.DateTimeField()
uts = models.DateTimeField()
id_users = models.ForeignKey('users.Users', models.DO_NOTHING, db_column='id_users')
num_subjects = models.IntegerField()
num_teachers = models.IntegerField()
class Meta:
managed = False
db_table = 'students'
bulk_create() method -
def saveCounts(cumulative_counts: pd.DataFrame, model: django.db.models.base.ModelBase) -> None:
records = cumulative_counts.to_dict('records')
model_instances = [model(
cts=timezone.now(),
uts=timezone.now(),
id_users=Users.objects.get(
id=record['id_users']),
num_subjects=record['num_subjects'],
num_teachers=record['num_teachers'],
) for record in records]
model.objects.bulk_create(model_instances)
I got this code, but I can't find a way to create a view that retrieve the allergies a patient has.
class Patient(models.Model):
user = models.OneToOneField(User, related_name='patient', on_delete=models.CASCADE)
id_type = models.CharField(max_length=300)
id_number = models.CharField(max_length=300)
creation_date = models.DateField(default=datetime.date.today)
class Allergie(models.Model):
name = models.CharField(max_length=300, default="X")
class PatientAllergies(models.Model):
patient = models.ForeignKey(Patient, related_name="patient_allergies", on_delete=models.CASCADE)
allergie = models.ForeignKey(Allergie, on_delete=models.CASCADE, null=True)
professional_contract = models.ForeignKey(ProfessionalContract, null=True ,on_delete=models.CASCADE)
You can span a ManyToManyField relation over your PatientAllergies model that acts as a junction table:
class Patient(models.Model):
user = models.OneToOneField(User, related_name='patient', on_delete=models.CASCADE)
id_type = models.CharField(max_length=300)
id_number = models.CharField(max_length=300)
creation_date = models.DateField(auto_now_add=True)
allergies = models.ManyToManyField(
'Allergie',
through='PatientAllergies'
)
# …
You can then for a Patient object p with:
p.allergies.all()
An alternative is to filter the Allergie objects with:
Allergie.objects.filter(patientallergies__patient=p)
or with the ManyToManyField:
Allergie.objects.filter(patient=p)
This is a part of models.py in my django app.
class User(models.Model):
user_id = models.AutoField(primary_key=True)
uuid = models.CharField(max_length=32)
name = models.CharField(max_length=10)
phone = models.CharField(max_length=20)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class UserForm(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True)
access_info = models.CharField(max_length=250)
etc_comment = models.CharField(max_length=250)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class UserAddress(models.Model):
user_address_id = models.AutoField(primary_key=True)
user = models.ForeignKey(User, on_delete=models.CASCADE)
address_name = models.CharField(max_length=100)
address_name_detail = models.CharField(max_length=100)
address_type = models.CharField(max_length=11)
address_coord = models.PointField()
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
I am using MySQL database and linked it to django database.
My question is how to get all three data together just in a single query.
As I know, I have to use django's prefetch_related or select_related method to get them together like this
objs = User.objects.select_related('userform').get(user_id=1)
But, what about getting them from three model classes?
Please, let me know if you have any idea.
class Students(models.Model):
id = models.BigAutoField(primary_key=True)
admission_no = models.CharField(max_length=255)
roll_no = models.CharField(unique=True, max_length=50, blank=True, null=True)
academic_id = models.BigIntegerField()
course_parent_id = models.BigIntegerField()
course_id = models.BigIntegerField()
first_name = models.CharField(max_length=20)
middle_name = models.CharField(max_length=20)
last_name = models.CharField(max_length=20)
user_id = models.BigIntegerField()
date_of_birth = models.DateField(blank=True, null=True)
date_of_join = models.DateField(blank=True, null=True)
class Courses(models.Model):
id = models.BigAutoField(primary_key=True)
parent_id = models.IntegerField()
course_title = models.CharField(max_length=50)
slug = models.CharField(unique=True, max_length=50)
tenant_user = models.ForeignKey('Users', models.DO_NOTHING, default='')
course_code = models.CharField(max_length=20)
course_dueration = models.IntegerField()
grade_system = models.CharField(max_length=10)
is_having_semister = models.IntegerField()
is_having_elective_subjects = models.IntegerField()
description = models.TextField()
status = models.CharField(max_length=8)
created_at = models.DateTimeField(blank=True, null=True)
updated_at = models.DateTimeField(blank=True, null=True)
class Meta:
managed = True
db_table = 'courses'
def __unicode__(self):
return self.course_title
class StudentProfileSerializer(ModelSerializer):
class Meta:
model = Students
depth = 0
fields = '__all__'
The first two tables/class contains the course and student table and the third contains the serializer. Can anyone please help how to query using the joins in django. I need to fetch the course_title from Courses table and first_name from Students table.
IMHO, you should review your models; course_id in Students should be a course=models.ForeignKey('Courses', ...); this way you can refer to the course title using dot notation;
student=Student.objects.filter(pk=...)
to refer to your required fields:
student.last_name, student.course.course_title
Besides, if I understood your models, you could get some incongruence... what if the value stored in course_parent_id in Students model is different from the value stored in parent_id in Courses model? maybe the first one is redundant.
To query a field from a related object use a double underscore. So you could do
Student.objects.filter(**kwargs).values('first_name', 'last_name', 'course__course_name')