How to combine forms for models with related objects? - django

I'm writing a program to store analyses for patient and I need to make a form with nested forests with next scheme
Each patient has an analyses results sheet
Each result sheet has date, patient (foreign key) and set of analyses values
Each set of analyses values has strict number and strict types of analyses
Each type of analyse has it's value, name and units
For example I want to create John's analyse result sheet for blood
Patient: John Date: 10.02.23
Set of values: 'Blood analysis'
Red blood cells:
3,23 10^9 Haemoglobin: 124 g/l
I've made models:
analysis/models.py
class AnalysisGroup(models.Model):
name = models.CharField(max_length=64)
class AnalysisType(models.Model):
name = models.CharField(max_length=256)
measurement = models.CharField(max_length=10)
analysis_group = models.ForeignKey(AnalysisGroup, on_delete=models.CASCADE)
class PatientAnalysisResultSheet(models.Model):
an_number = models.PositiveBigIntegerField()
date = models.DateField()
time = models.TimeField()
patient = models.ForeignKey('patient.Patient', on_delete=models.CASCADE)
analyzes_group = models.ForeignKey(AnalysisGroup, on_delete=models.CASCADE)
class PatientAnalysis(models.Model):
sheet = models.ForeignKey(PatientAnalysisResultSheet, on_delete=models.CASCADE)
analysis = models.ForeignKey(AnalysisType, on_delete=models.CASCADE)
value = models.FloatField()
patient/models.py:
class Patient(models.Model):
hist_number = models.IntegerField(unique=True)
last_name = models.CharField(max_length=32)
first_name = models.CharField(max_length=32)
def get_absolute_url(self):
return reverse('patient:patient-detail', kwargs={'pk': self.pk})
Now how can I make a form to have an opportunity go on patients page and then add an group of analyses (blood analysis) at once?

Related

How can I filter the value selected in a Django model form based on a certain data condition?

Good day!
I have a model table in order to add data to this model.
[Citizen_2]
I would like users to enter their country of residence first, it's like a simple one-field form.
And then a form of two fields - where it is proposed to select the country of residence from the value already entered in the (name_country) field.
For example, I have users added three countries there.
Then they add the cities - for those respective countries.
In the drop-down form field, select a country and write down your city there. And send the data to the model table.
It is necessary that the data be saved in such a way that the city corresponds to the country to which the user wrote it down in the form.
This is then used in the form to fill in the data.
By country and its corresponding city in the main form.
How can I make it in the form of a model [Citizen_2]
the city of the corresponding country was chosen.
From data previously filled in by users?
Any information or help would greatly save me, please.
Citizen_2
class Country(models.Model):
name_country = models.CharField(max_length=150, db_index=True)
def __str__(self):
return self.name_country
class City(models.Model):
name_city = models.CharField(max_length=150, db_index=True)
def __str__(self):
return self.name_city
class Citizen_1(models.Model):
name_country = models.ForeignKey(Country, on_delete=models.CASCADE)
name_city = models.CharField(max_length=150, db_index=True)
def __str__(self):
return self.name_country, self.name_city
class Citizen_2(models.Model):
name_country = models.ForeignKey(Country, on_delete=models.CASCADE)
name_city = models.ForeignKey(City, on_delete=models.CASCADE)
birthday = models.DateField()
profession = models.CharField(max_length=150)
hobby = models.CharField(max_length=150)

How to change field value dynamically depended on dropdown selection in django

I've been searching Google, but couldn't find a simple answer to this problem:
I have a django models that stores students information and three other models like this:
class Level(models.Model):
name = models.CharField(max_length=50)
class Pricing(models.Model):
level = models.ForeignKey(Level, on_delete=models.PROTECT)
price = models.PositiveSmallIntegerField(default=0)
class Enrollment(models.Model):
student = models.ForeignKey(Student, on_delete=models.PROTECT)
level = models.ForeignKey(Level, on_delete=models.CASCADE)
date_enrolled = models.DateField()
price = models.PositiveSmallIntegerField(default=0)
I want the Enrollment.price field to be populated dynamically depending on Enrollment.level field value. In javascript, it amounts to setting an event listener to Enrollement.level, but I can't find the equivalent in django.
hi you can modify your save method to fill automatically field price from Level model
Enrollment.level
class Enrollment(models.Model):
student = models.ForeignKey(Student, on_delete=models.PROTECT)
level = models.ForeignKey(Level, on_delete=models.CASCADE)
date_enrolled = models.DateField()
price = models.PositiveSmallIntegerField()
def save(self,*args,**kwargs):
self.price = Pricing.objects.get(level=self.level).price
super().save(*args,*kwargs)
but I recommend to rewrite your model like above example because its simple and you can access to price of every level directly
like Enrollment.level.price
class Level(models.Model):
level = models.CharField(max_length=50,unique=True)
price = models.PositiveSmallIntegerField(default=0)
class Enrollment(models.Model):
student = models.ForeignKey(Student, on_delete=models.PROTECT)
level = models.ForeignKey(Level, on_delete=models.CASCADE)
date_enrolled = models.DateField()
I hope it helped you

django models related manager

I want to develop DJANGO Application for rooms booking.
I want to use following TWO models.
class Room(models.Model):
room_no = models.IntegerField()
remarks = models.CharField(max_length=100)
def __str__(self):
return self.remarks
class Roombooking(models.Model):
room = models.ForeignKey(Room, related_name= 'roombookingforroom', on_delete=models.CASCADE)
booked_for_date = models.DateField(blank=True, null=True)
booked_by = models.TextField(max_length=1000, default='')
remarks = models.CharField(max_length=100,)
class Meta:
constraints = [
models.UniqueConstraint(
fields=["suit", "booked_for_date"],
name="unique_room_date",
),
]
def __str__(self):
return self.room.remarks
To avoid assigning one room to 2 different persons on any day, “ UniqueConstraint” is used.
Now, how to query the list of rooms which are vacant from DATE1 to DATE2
You can just filter the room booking by date
gte = greater than or equal to
lte = lower than or equal to
query = Roombooking.objects.filter(booked_for_date__gte=DATE1, booked_for_date__lte=DATE2)
*Note that DATE1 and DATE2 should be datetime type
You can have a look on official documentation

JOIN Two table in DJANGO with aggregate

I've been playing around with django for a month now and i'm stuck with JOINING Two tables with Aggregate with it. Here's my models.py
class Student(models.Model):
student_number_format = RegexValidator(regex=r"^20{1,2}[1-2][0-9]-[0-9]{6}", message="Please enter a valid student number (example:2019-123456)")
student_number = models.CharField(validators=[student_number_format], max_length=11, blank=True, unique=True, help_text="Student number must be this format 20YY-99999")
student_course = models.ForeignKey(Course, on_delete=models.CASCADE)
first_name = models.CharField(max_length=255)
middle_initial = models.CharField(max_length=2)
last_name = models.CharField(max_length=255)
profile_picture = models.ImageField(upload_to=user_directory_path)
date_registered = models.DateTimeField(default=timezone.now)
class DataSets(models.Model):
student_info = models.ForeignKey(Student, on_delete=models.CASCADE)
dataset_image = models.ImageField(upload_to=dataset_directory_path)
date_upload = models.DateTimeField(default=timezone.now)
In here i have two models the DataSets class have a Foreign Key to Student. And i want to show only is Students that have 5 or more data inside DataSets. Here's the SQL representation:
SELECT Count(student_info) as Count, A.first_name as Name
FROM Student A
JOIN DataSets B ON A.id = B.student_info_id
WHERE Count >= 5
You can do this with select_relatedlink . I hope following query will work.
DataSets.objects.select_related('student_info').annotate(
entries=models.count()).filter(entries__gte=5)

Django- manytomany model relationships

I'm still learning about how to setup up relational databases. I'm trying to create a db that tracks universities, departments, and their programs. My question is a relationship one. Each university might have one or more departments. This relationship should then be a many to many. Each department may have one or more programs, so I can see the relationship between the department and the programs being many to many.
The problem that I have is if I want to have a department that belongs to a university, I feel like I should use an intermediary to attach a program to that department. But then, if I want to add another program to the same department, I would end up having two of the same departments belonging to the one university. This doesn't seem right.
In other words:
class Department(models.Model):
'''
'''
code = models.CharField(max_length=80,unique=True)
description = models.CharField(max_length=255)
def __unicode__(self):
return '{}'.format(self.description)
class Universities(models.Model):
'''
'''
code = models.CharField(max_length=80,unique=True)
description = models.CharField(max_length=255)
departments = models.ManyToManyField(Department,through='UniversityHasDepartment')
class Program(models.Model):
'''
'''
code = models.CharField(max_length=80,unique=True)
description = models.CharField(max_length=255)
def __unicode__(self):
return '{}'.format(self.description)
class UniversityHasDepartment(models.Model):
university = models.ForeignKey(Universities)
department = models.ForeignKey(Department)
program = models.ForeignKey(Program)
I think you want to use foreign keys. (one to many relationships).
Each university can have multiple departments but a department can only have 1 university.
Each department can have multiple programs but a program can only have 1 department.
class University(models.Model):
name = models.CharField(max_length=80,unique=True)
description = models.CharField(max_length=255)
class Department(models.Model):
university = models.ForeignKey(University, related_name='departments')
name = models.CharField(max_length=80,unique=True)
description = models.CharField(max_length=255)
class Program(models.Model):
department = models.ForeignKey(Department, related_name='programs')
name = models.CharField(max_length=80,unique=True)
description = models.CharField(max_length=255)