I can use some help on a query using 3 tables. Here is what my models contains.
class VolunteerRecord(models.Model):
eventname = models.CharField(help_text=_('Name of the event'),max_length=256, blank=False, default='')
category = models.CharField(max_length=256, blank=False, choices=CATEGORY_CHOICES)
hours = models.FloatField(blank=False)
date=models.DateField(help_text=_('Enter the date of the event'),validators=MaxValueValidator(limit_value=date.today)])
mileage = models.FloatField(blank=True, null=True)
owner = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True)
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
streetaddress1 = models.CharField(blank=True, max_length=256)
streetaddress2 = models.CharField(blank=True, max_length=256)
city = models.CharField(blank=True, max_length=30)
state = models.CharField(max_length=256, blank=False, choices=US_STATES)
zipcode = models.CharField(blank=True, max_length=15)
county = models.CharField(max_length=256, blank=False, choices=STATE_COUNTIES)
I would like to filter all VolunteerRecords where the owner's county = request.user's county
So far I have... (not sure what I am suppose to put where my ??? are)
def history(request):
current_user_county = request.user.profile.county
records = VolunteerRecord.objects.filter(????=current_user_county)
I was able to figure it our with your help.
records = VolunteerRecord.objects.filter(owner__profile__county=request.user.profile.county)
Related
there are 3 models, how to form a request to retrieve all LocationCompany with a specific city or sector, + DomainService domain + Service service_type, name
name = models.CharField(max_length=20, blank=True, null=True)
service_type = models.ForeignKey(Service_type, on_delete=models.CASCADE)
price = models.DecimalField(max_digits=10, decimal_places=0)
slug = models.SlugField(max_length=30)
class DomainService(models.Model):
domain = models.CharField(max_length=30)
sercices = models.ManyToManyField(Service, blank=True)
title = models.CharField(max_length=200, blank=True)
short_description = models.CharField(max_length=500, blank=True)
long_description = models.CharField(max_length=1000, blank=True)
specialization = models.ForeignKey(SpecializationService, on_delete=models.SET_NULL, blank=True, null=True)
slug = models.SlugField(max_length=30)
class LocationCompany(models.Model):
company = models.ForeignKey(MyUser, on_delete=models.CASCADE, blank=True, null=True)
doctors = models.ManyToManyField(MyUser, blank=True, related_name='company_doctors')
domain = models.ManyToManyField(DomainService, blank=True)
city = models.CharField(max_length=30)
sector = models.CharField(max_length=30, blank=True, null=True)
street = models.CharField(max_length=30, blank=True, null=True)
google_maps_link = models.CharField(max_length=500, blank=True, null=True)
slug = models.SlugField(max_length=30)
slug_sector = models.SlugField(max_length=30)```
Something like:
from django.db.models import Q
location_companies = LocationCompany.objects.filter(
Q(city='some city') | Q(sector='some sector'), # or query for city or sector
domain__domain = 'some domain',
sercices__name = 'some service',
sercices__service_type = 'some service type',
).distinct() # add this to ensure uniqueness
Note, best practice is to give your model relations more intuitive names, for example:
class LocationCompany(models.Model):
domain_services = models.ManyToManyField(
DomainService,
...,
related_name = 'location_companies'
)
This then changes the above query to something like:
location_companies = LocationCompany.objects.filter(
domain_services__domain = 'some domain',
...
)
I have 2 models one defines all the all the devices that I have, and the other stores the information that the devices are obtaining. The code of they is the following,
class Device(models.Model):
dev_eui = models.CharField(max_length=16, primary_key=True)
producer = models.CharField(max_length=20, blank=True, null=True)
model = models.CharField(max_length=20, blank=True, null=True)
firmware = models.CharField(max_length=10, blank=True, null=True)
dev_name = models.CharField(max_length=20, blank=True, null=True)
description = models.CharField(max_length=40, blank=True, null=True)
fixed = models.BooleanField()
dev_lat = models.FloatField(null=True, blank=True)
dev_lon = models.FloatField(null=True, blank=True)
deco_name = models.CharField(max_length=20)
fleet_id = models.IntegerField(null=True, blank=True)
class DevData(models.Model):
data_uuid = models.UUIDField(primary_key=True, default=uuid.uuid1, editable=False)
data_id = models.IntegerField()
dev_eui = models.CharField(max_length=16)
gateway = models.CharField(max_length=25)
data_timestamp = models.DateTimeField()
rssi = models.IntegerField()
snr = models.IntegerField()
datarate = models.CharField(max_length=15)
frequency = models.IntegerField()
seq = models.IntegerField()
data_1 = models.FloatField()
data_2 = models.FloatField(null=True, blank=True)
data_3 = models.FloatField(null=True, blank=True)
data_4 = models.FloatField(null=True, blank=True)
data_5 = models.FloatField(null=True, blank=True)
data_6 = models.FloatField(null=True, blank=True)
data_7 = models.FloatField(null=True, blank=True)
Actually what I want is show a table in my template, combining all the data from devData and adding the dev_name and fleet_id from devices.
Now what I'm doing is obtaining all the data and in the template filtering it. But I'm sure it's better and easier doing this in the views.py, but I don't know how.
Reading some info, I found the union() function but it's not working and I'm not sure if is the best option,
#login_required(login_url='/user_app/login/')
def user_data(request):
dev_data = DevData.objects.all()
devices = Device.objects.all()
test = DevData.objects.all().values_list(
"dev_eui"
).union(
Device.objects.all().values_list(
"dev_eui"
))
ctx = {'DevData':dev_data,'Devices':devices, 'Test':test}
return render(request, template_name='data.html', context=ctx)
This join shows nothing.
Can somebody help me? Thank very much!
You need a foreign key relating the two models.
class Device(models.Model):
dev_eui = models.CharField(max_length=16, primary_key=True)
class DevData(models.Model):
device = models.ForeignKeyField(Device, related_name='dev_data', on_delete=models.CASCADE)
data_uuid = models.UUIDField(primary_key=True, default=uuid.uuid1, editable=False)
data_id = models.IntegerField()
# This is not needed, it can be accessed via instance.device.dev_eui now
# dev_eui = models.CharField(max_length=16)
Then to get all of the DevData instances for a particular device:
for device in Device.objects.all():
x = device.dev_data.all()
Please read the documentation to better understand relationship fields.
Current Database Schema -
I have these 3 tables, Curriculum, Assignment, and Student. Every Student is assigned a Curriculum through a ForeginKey relationship between Student and Curriculum. Every
Assignment possesses the same relation with the Curriculum using a ForeginKey.
Problem Statement -
There are around 100 Assignments for each Curriculum, the problem is, some students need to be exempt from some assignments, so I want a way that I can exempt a Student from Assignments 1, 2, and 3 but have the rest of the students do the assignment 1, 2 and 3.
My solution that failed -
What I tried was, creating a ManyToManyField in Student table in relation to Assignment table. However, having to add hundreds of assignments manually would be ridiculously time-consuming for each student.
class Curriculum(models.Model):
name = models.CharField(max_length=50, null=False)
subject = models.CharField(max_length=30, choices=SUBJECT)
grade_level = models.CharField(max_length=20, choices=CURRICULUMGRADE, null=False)
tracking = models.CharField(max_length=20, choices=TRACKING, null=False)
required = models.CharField(max_length=20, null=True)
recorded_from = models.CharField(max_length=20, choices=RECORDED, null=False)
semesterend = models.CharField(max_length=50, null=True)
username = models.CharField(max_length=50, null=True)
password = models.CharField(max_length=50, null=True)
loginurl = models.CharField(max_length=100, null=True)
weight = models.IntegerField(null=True)
level = models.CharField(max_length=20, choices=LEVEL, null=False)
class Student(models.Model):
epicenter_id = models.CharField(
null=False, blank=False, unique=True, max_length=10
)
last_name = models.CharField(null=False, max_length=50)
first_name = models.CharField(null=False, max_length=50)
email = models.EmailField(null=False, max_length=120)
phone_number = models.CharField(null=False, max_length=50)
additional_email = models.EmailField(max_length=120, null=True)
additional_phone_number = models.CharField(max_length=20, null=True)
grade = models.CharField(max_length=20, choices=GRADELEVEL, null=False)
curriculum = models.ForeginKey('curriculum', null=True, blank=True, on_delete=models.SET_NULL)
class Assignment(models.Model):
standard = models.ManyToManyField(
Standard)
curriculum = models.ForeignKey(
Curriculum, on_delete=models.CASCADE, related_name="curriculum_assignment"
)
name = models.CharField(max_length=500, null=False)
description = models.CharField(max_length=500, null=False)
status = models.CharField(max_length=30, choices=STATUS, null=False)
type_of = models.CharField(max_length=30, choices=TYPE, null=False)
Alright, so the best solution I could think of was creating another table to store all the exempted assignments, called ExemptAssignements.
models.py
class ExemptAssignments(models.Model):
student = models.ForeginKey('student', null=True, blank=True, on_delete=models.SET_NULL)
assignments = models.ManyToMany('assignment', null=True, blank=True)
Now anytime I want to exempt the students from any Assignments, I can manually select them through the admin panel, as well the Student who's being exempted.
Now to get a list of all the assignments excluding the ones I have exempted I can simply use.
student = Student.objects.first()
Assignment.objects.filter(curriculum=student.curriculum).exclude(id__in=[x.id for x i in ExemptAssignment.objects.filter(student=student).assignment.all()]
And the above query will only show the Assignments which haven't been exempted.
models.py:
class Department(models.Model):
department_id = models.AutoField(primary_key=True)
department_n_key = models.CharField(max_length=30,blank=True,unique=True)
hospital_short_name = models.CharField(max_length=20)
department_name = models.CharField(max_length=50)
class EmployeesMaster(models.Model):
employee_id = models.AutoField(primary_key=True)
employee_n_key = models.CharField(max_length=30,blank=True,unique=True)
first_name = models.CharField(max_length=30)
middle_name = models.CharField(max_length=30, blank=True, null=True)
last_name = models.CharField(max_length=30, blank=True, null=True)
gender = models.CharField(max_length=12, blank=True, null=True)
class PatientMaster(models.Model):
patient_id = models.AutoField(primary_key=True)
patient_n_key = models.CharField(max_length=30,blank=True,unique=True)
first_name = models.CharField(max_length=30)
middle_name = models.CharField(max_length=30, blank=True, null=True)
last_name = models.CharField(max_length=30, blank=True, null=True)
age = models.IntegerField(blank=True, null=True)
views.py
i need to apply this in django:
SELECT * FROM appointment_master WHERE patient_type='something' andappointment_master.department_n_key IN (SELECT department.department_n_key FROM department WHERE department.department_name='something')
help somebody to apply this in django
It's not optimal but you can do it in two Queries
departments_list= Department.objects.filter(departmen_name='foo').values_list('department_n_key', flat=True)
apointment_master = YourModel.objects.filter(patient_type='bar', department_n_key__in=departments_list)
How is "translation" for following query to django queryset?
SELECT guid FROM feedme_feeditem
WHERE feed_id IN
(SELECT id FROM feedme_feed WHERE country_id IN
(SELECT id FROM feedme_country WHERE name='NL'))
models.py
class Country(models.Model):
name = models.CharField(max_length=250, blank=True)
class Category(models.Model):
name = models.CharField(max_length=250, blank=True)
slug = models.SlugField(blank=True, null=True, editable=False)
user = models.ForeignKey(User, blank=True, null=True)
country = models.ForeignKey(Country, blank=True, null=True)
class Feed(models.Model):
link = models.CharField(blank=True, max_length=450)
url = models.CharField(blank=True, max_length=450)
title = models.CharField(blank=True, null=True, max_length=250)
category = models.ForeignKey(Category, blank=True, null=True)
user = models.ForeignKey(User, blank=True, null=True)
last_update = models.DateField(blank=True, null=True, editable=False)
country = models.ForeignKey(Country, blank=True, null=True)
class FeedItem(models.Model):
title = models.CharField(max_length=350, blank=True)
link = models.URLField(blank=True)
content = models.TextField(blank=True)
feed = models.ForeignKey(Feed, blank=True, null=True)
read = models.BooleanField(default=False)
guid = models.CharField(max_length=255)
pub_date = models.DateTimeField()
To make more simple I already tried add country = models.ForeignKey(Country, blank=True, null=True) to FeedItem class but does't work how i expected.
guids = FeedItem.objects.filter(feed__country__name = 'NL')