I am trying to create an app, that handles laboratory analyses - something like similar Laboraotory Information System (LIS)
The issue is that i dont know which approach to take.
I am plannin to make it as follows:
"ANALYSES" table - consisting of "name", "ID" of analyses
"PROBES" table - consisiting of "name", "ID", "reference", "VALUE", "measurement".
Also the PROBES will have the field which links it to certain "ANALYSES" instance.
SO it will be like "ANALYSES #1" -> "PROBE1", "PROBE2", "PROBE3"
"ANALYSES #2" -> "PROBE1", "PROBE3"
And so on.
The operator should be capable of adding new analyses and adding probes to this analyses via frontend in one "view" - like "LAB settings" and in another view - to enter values to instances of this analyses (all analyses instances will be linked to some "VISIT" - the service case)
What approach should i take planning the app and models? will it be some Meta classes or just multiple tables linked "manytoone" or "manytomany"?
Will be gratefull for any advice!
Nothing about this seems particularly complex that a ManyToOne relationship can't handle. Your models would look like this:
class Visit(models.Model):
...
class Analysis(models.Model):
visit = models.ForeignKey(Visit, ...
...
class Probe(models.Model):
analysis = models.ForeignKey(Analysis, ...
...
If many probes can attach to different analyses or analyses to visits then use a ManyToManyField instead of ForeignKey, note that processing m2m in Django works differently to m21 relations.
https://docs.djangoproject.com/en/4.0/topics/db/examples/many_to_one/
https://docs.djangoproject.com/en/4.0/topics/db/examples/many_to_many/
Thanks for answer!
Currently i am doing something similar to this, if someone interested.
Maybe there are easier ways, but it suits my needs so far.
import uuid
from django.db import models
# Create your models here.
class Patient(models.Model):
class Gender(models.TextChoices):
male = "Муж"
female = "Жен"
surname = models.CharField("Фамилия", max_length=200)
name = models.CharField("Имя", max_length=200)
fathname = models.CharField("Отчество", max_length=200)
created = models.DateTimeField("Добавлен", auto_now_add=True)
id = models.AutoField("Идентификатор", primary_key=True)
dateofbirth = models.DateField("Дата рождения", null=True, blank=True)
gender = models.CharField("Пол", max_length=3, choices=Gender.choices, default=Gender.male)
snils = models.DecimalField("СНИЛС", max_digits=11, decimal_places=0, null=True, blank=True)
class Meta:
ordering = ['-created']
def returnFIO(self):
return self.surname + " " + self.name + " " + self.fathname
def returnAge(self):
import datetime
return (datetime.date.today() - self.dateofbirth) / 365
def __str__(self):
return self.surname + " " + self.name + " " + self.fathname
class Visit(models.Model):
patient = models.ForeignKey(Patient, on_delete=models.CASCADE, verbose_name="Пациент")
id = models.AutoField("Идентификатор", primary_key=True)
created = models.DateTimeField("Добавлен", auto_now_add=True)
class Meta:
ordering = ['-created']
def returnCreated(self):
return self.created
def __str__(self):
return str(self.id) + " / " + str(self.created)
from django.db import models
import uuid
from patients.models import Visit
# Create your models here.
class Analiz(models.Model):
name = models.CharField(max_length=200, blank=True, null=True)
description = models.CharField(max_length=200, blank=True, null=True)
id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False)
def __str__(self):
return str(self.name)
class AnalizInst(models.Model):
analiz = models.ForeignKey(Analiz, on_delete=models.CASCADE, null=True)
id = models.AutoField(primary_key=True)
created = models.DateTimeField(auto_now_add=True)
related_to_visit = models.ForeignKey(Visit, on_delete=models.CASCADE, null=True)
def __str__(self):
return str(self.analiz) + ' / ' + str(self.id)
class Measurement(models.Model):
id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False)
name = models.CharField(max_length=200, blank=True, null=True)
def __str__(self):
return self.name
class Probe(models.Model):
name = models.CharField("Название теста", max_length=200, blank=True, null=True)
description = models.CharField("Описание", max_length=200, blank=True, null=True)
id = models.UUIDField("Идентификатор", default=uuid.uuid4, unique=True, primary_key=True, editable=False)
related_to_analiz = models.ForeignKey(Analiz, on_delete=models.CASCADE, null=True, verbose_name="Привязка к анализу")
digits = models.IntegerField("Цифр после запятой", null=True, blank=True)
measurement = models.ForeignKey(Measurement, on_delete=models.SET_NULL, null=True, blank=True, verbose_name="Измерение")
probeIsDigital = models.BooleanField("Числовой", default=True)
referenceText = models.CharField("Референс текст", max_length=50, blank=True, null=True)
referenceMin = models.DecimalField("Референс MIN", max_digits=10, decimal_places=5, null=True, blank=True)
referenceMax = models.DecimalField("Референс MAX", max_digits=10, decimal_places=5, null=True, blank=True)
defaultInUse = models.BooleanField("Включен по умолчанию", default=True)
hl7Name = models.CharField("Имя в анализаторе", max_length=200, blank=True, null=True)
defaultText = models.CharField("Текст значения по умолчанию", max_length=200, blank=True, null=True)
def __str__(self):
return str(self.name)
class ProbeInst(models.Model):
value = models.DecimalField("Значение", max_digits=10, decimal_places=5, null=True, blank=True)
textvalue = models.CharField("Текстовое значение", max_length=200, blank=True, null=True)
probe = models.ForeignKey(Probe, on_delete=models.CASCADE, null=True, verbose_name="Тест")
id = models.AutoField("Идентификатор", primary_key=True)
related_to_analyse = models.ForeignKey(AnalizInst, on_delete=models.CASCADE, null=True, verbose_name="Привязка к анализу")
created = models.DateTimeField("Создан", auto_now_add=True)
inUse = models.BooleanField("В работе", default=True)
def __str__(self):
return str(self.probe)
Further i am planning to build some UI and forms input for manual input and make some integrations with HL7 standard to load data directly from lab analyzers.
Django is the best thing that happened to me so far in programming)
Related
I am joining the ClientDetails, AssignmentTable and CallDetails table to get a view as to which telecaller a particular client has been assigned to and get the latest call details as well. However I am unable to accomplish that using django ORM.
ISSUE:
I am trying to access the fields inside the assignment table and call table but I am getting only the ids and not the other fields.
Question:
How do I extract all the columns from the assignment and call details table which has the client id as 1?
This is the SQL Query that I am trying to come up with:
SELECT t1.uid, t1.phone_number, t1.client_name, t1.base, t1.location, t2.assigner, t2.bpo_agent, t2.cro_agent, t3.bpo_status_id, t3.cro_status_id, t3.agent_id_id
FROM public.bpo_app_clientdetails t1
LEFT JOIN public.bpo_app_assignmentdetails t2 ON t1.uid = t2.client_id_id
LEFT JOIN public.bpo_app_calldetails t3 ON t1.uid = t3.client_id_id;
Below is the model file:
class ClientDetails(models.Model):
uid = models.AutoField(primary_key=True)
phone_number = PhoneNumberField(unique=True)
client_name = models.CharField(max_length=50, blank=True, null=True)
base = models.CharField(max_length=50, blank=True, null=True)
location = models.CharField(max_length=50, blank=True, null=True)
class Meta:
verbose_name_plural = "Client Contact Detail Table"
def __str__(self):
return f"{self.phone_number}, {self.client_name}"
class AssignmentDetails(models.Model):
uid = models.AutoField(primary_key=True)
client_id = models.ForeignKey(
ClientDetails,
on_delete=models.PROTECT,
related_name='assignment_details'
)
date_and_time = models.DateTimeField(auto_now_add=True, blank=True)
assigner = models.ForeignKey(
User,on_delete=models.PROTECT,
related_name='AssignerAgent',
db_column='assigner',
)
bpo_agent = models.ForeignKey(
User,on_delete=models.PROTECT,
related_name='bpoAgent',
db_column='bpo_agent',
)
cro_agent = models.ForeignKey(
User,on_delete=models.PROTECT,
related_name='croAgent',
db_column='cro_agent',
)
class Meta:
verbose_name_plural = "Client Assignment Detail Table"
def __str__(self):
return f"{self.uid}"
class CallDetails(models.Model):
uid = models.AutoField(primary_key=True)
date_and_time = models.DateTimeField(auto_now_add=True, blank=True)
client_id = models.ForeignKey(
ClientDetails,
on_delete=models.PROTECT,
related_name='call_details'
)
agent_id = models.ForeignKey(EmployeeDetails_lk,on_delete=models.PROTECT)
bpo_status = models.ForeignKey(BpoStatus_lk,on_delete=models.PROTECT, blank=True, null=True)
cro_status = models.ForeignKey(CroStatus_lk,on_delete=models.PROTECT, blank=True, null=True)
required_loan_amt = models.CharField(max_length=50, blank=True, null=True)
remarks = models.CharField(max_length=500, blank=True, null=True)
loan_program = models.ForeignKey(LoanProgram_lk, on_delete=models.PROTECT, blank=True, null=True)
disbursement_bank = models.ForeignKey(Banks_lk, on_delete=models.PROTECT, limit_choices_to={'loan_disbursement_status': True}, blank=True, null=True)
class Meta:
verbose_name_plural = "Client Call Detail Table"
def __str__(self):
return f"{self.uid}"
>>> qry=ClientDetails.objects.values('assignment_details','call_details').filter(uid=1)
>>> qry
<QuerySet [{'assignment_details': 1, 'call_details': None}]>
>>> print(a.query)
SELECT "bpo_app_assignmentdetails"."uid", "bpo_app_calldetails"."uid" FROM "bpo_app_clientdetails" LEFT OUTER JOIN "bpo_app_assignmentdetails" ON ("bpo_app_clientdetails"."uid" = "bpo_app_assignmentdetails"."client_id_id") LEFT OUTER JOIN "bpo_app_calldetails" ON ("bpo_app_clientdetails"."uid" = "bpo_app_calldetails"."client_id_id") WHERE "bpo_app_clientdetails"."uid" = 1
You can use prefetch_related() to achieve this. I just use some sample models here for better understanding.
class Company(models.Model):
name = models.CharField(null=True, blank=True, max_length=100)
class Project(models.Model):
name = models.CharField(null=True, blank=True, max_length=100)
company = models.ForeignKey(Company, on_delete=models.CASCADE)
class Employee(models.Model):
name = models.CharField(null=True, blank=True, max_length=100)
company = models.ForeignKey(Company, on_delete=models.CASCADE)
In your views.py function write the below lines to get the desired results
companies = Company.objects.filter(id=1).prefetch_related('project_set', 'employee_set')
for company in companies:
print(company.project_set.values()) # This will print this company projects
print(company.employee_set.values()) # This will print this company employees
Note: If you use related_name in your ForeignKey relationship, make sure that you access with that name instead of model_set inside prefetch_related()
I want to create a Model in which I can store the same models as for example in a folder there can be several folders.
I tried like this:
class Service(models.Model):
name = models.TextField(default="")
price = models.IntegerField(blank=True, null=True)
def __str__(self):
return self.name
class ServiceType(models.Model):
services_types = models.ManyToManyField(ServiceType, null=True, blank=True)
services = models.ManyToManyField(Service, null=True, blank=True)
name = models.TextField(default="")
But it didn't work. How can this problem be solved?
If you want to reference same model then you have to use quotation 'ModelName' like this.
So your code will be like:
class Service(models.Model):
name = models.TextField(default="")
price = models.IntegerField(blank=True, null=True)
def __str__(self):
return self.name
class ServiceType(models.Model):
services_types = models.ManyToManyField('ServiceType', null=True, blank=True)
services = models.ManyToManyField(Service, null=True, blank=True)
name = models.TextField(default="")
** I just need one more table join in my query **
I want to get sales of logged-in users with order detail and shipping address.
I am getting sales of current user through this query but i also want get shipping address.
orderitems = OrderItem.objects.filter(
product__user=request.user, order__complete=1).order_by('-date_orderd')
Now i want to get also address, city and state from the Shippingaddress model.
I attached the models below.
this is my current result.
My models:
Order Model:
class Order(models.Model):
user = models.ForeignKey(
User, on_delete=models.CASCADE, blank=True, null=True)
date_orderd = models.DateTimeField(auto_now_add=True)
complete = models.BooleanField(default=False, null=True, blank=False)
transaction_id = models.CharField(max_length=200, null=True)
# product = models.ManyToManyField(OrderItem)
def __str__(self):
return str(self.id)
Order items Model:
class OrderItem(models.Model):
product = models.ForeignKey(
Product, on_delete=models.CASCADE, blank=True, null=True)
order = models.ForeignKey(
Order, on_delete=models.SET_NULL, blank=True, null=True)
quantity = models.IntegerField(default=0, null=True, blank=True)
date_orderd = models.DateTimeField(auto_now_add=True)
user = models.ForeignKey(
User, on_delete=models.SET_NULL, blank=True, null=True)
price = models.FloatField(blank=True, null=True)
def __str__(self):
return str(self.product)
Shipping Address Model:
class ShippingAddress(models.Model):
user = models.ForeignKey(
User, on_delete=models.CASCADE, blank=True, null=True)
order = models.ForeignKey(
Order, on_delete=models.CASCADE, blank=True, null=True)
name = models.CharField(max_length=150)
address = models.CharField(max_length=150)
city = models.CharField(max_length=150)
state = models.CharField(max_length=150)
zipcode = models.CharField(max_length=150)
date_orderd = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.address
What you are looking for is "Select from multiple tables in one query with Django". You can take a look at the answers here.
Why not add another query like the one below
shp_address = ShippingAddress.objects.filter(product__user=request.user)
and if needed send to the client side as part of context, see below
context = {
'orderitems': orderitems,
'shp_address': shp_address
}
Hello all here I am new in Django till now I worked with simple models and generic views.
Now I have two models, Server and InventaryGroups, where InventoryGroups is group of Servers.
class Server(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
name = models.CharField(max_length=20, null=True)
hostname = models.CharField(max_length=50, null=True, blank=True)
ip = models.GenericIPAddressField()
ip2 = models.GenericIPAddressField(null=True, blank=True)
user_name = models.CharField(max_length=20, null=True)
password = models.CharField(max_length=200, null=True, blank=True)
ssh_key = models.FileField(null=True, blank=True)
status = models.CharField(max_length=10, null=True, blank=True)
last_login_time = models.DateTimeField(null=True, blank=True)
last_login_from = models.GenericIPAddressField(null=True, blank=True)
def __str__(self):
return str(self.user) + " - " + self.name
class InventoryGroups(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
name = models.CharField(max_length=20, null=True)
host = models.ManyToManyField(Server)
description = models.CharField(max_length=100, null=True, blank=True)
def get_hosts(self):
if self.host:
hostlist = []
for name in self.host.all():
hostlist.append(name)
return hostlist
def __str__(self):
return str(self.user) + " - " + self.name
What I am trying to do is limit my Server (server list) according to User. Like this:
You can see all servers in hostlist.
But I want to show only those Severs which are added by authenticated users or users selected in InventoryGroups.user
I have a table that displays a list of "leads" which are rendered fine. There is also a related model which is called "Leadupdate" that is related to "lead" model that is used in the table. There is a many to one relationship from Leadupdate to lead with a foreign key. I want to display all the related updates for the individual "leads" in one of the updates column. There are several examples online for following forward relationship through foreign key but haven't found one for reverse yet. Here is one example of said relationship Accessor forward look up.
EDIT: Look up will be done on a Django-tables2 module instance table. I am not asking reverse look up on a model but doing it in context of Django-tables2.
Models.py:
class lead(models.Model):
slug = models.SlugField(unique=True,blank=True, null=True)
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100, blank=True, null=True)
business_name = models.CharField(max_length=100,blank=True, null=True)
email = models.EmailField(max_length=75, blank=True, null=True)
phone_number = models.CharField(max_length=20, blank=True, null=True)
address = models.CharField(max_length=150, blank=True, null=True)
city = models.CharField(max_length=50, blank=True, null=True)
state = models.CharField(max_length=10, blank=True, null=True)
zipcode = models.CharField(max_length=5, blank=True, null=True)
submission_date = models.DateTimeField(auto_now_add=True, blank=True)
assigned_to = models.ManyToManyField(Listing,blank=True, null=True, related_name="leads")
requested_software = models.CharField(max_length=50, blank=True, null=True)
type_of_business = models.CharField(max_length=30, choices=TYPE_OF_BUSINESS, default='Bar', blank=True, null=True)
time_frame = models.CharField(max_length=10, choices=TIME_FRAME, default='1')
comments = models.TextField(blank=True, null=True)
def __unicode__(self):
return self.business_name
#models.permalink
def get_absolute_url(self):
return('listing_detail', (),{'slug' :self.slug,})
def save(self, *args, **kwargs):
if not self.slug:
self.slug = slugify(self.business_name)
super(lead, self).save(*args, **kwargs)
class Leadupdate(models.Model):
CONFIDENCE_LEVEL = (
('HOT', 'HOT'),
('COLD', 'COLD'),
)
LEAD_VALUE = (
('1K3K', '1K-3K'),
('5K10K', '5K-10K'),
('10K20K', '10K-20K'),
('20K50K', '20K-50K'),
('50KUP', '5OK-UP'),
)
ESTIMATED_CLOSING = (
('1w4w', '1-4 Weeks'),
('1m3m', '1-3 Months'),
('3m6m', '3-6 Months'),
('6m+', '6+ Months'),
)
updatedate = models.DateTimeField(auto_now_add=True)
update = models.TextField(blank=True, null=True)
updatefrom = models.ForeignKey(Listing, related_name="update_from", blank=True, null=True)
lead = models.ForeignKey(lead, related_name="related_update",blank=True, null=True)
lead_confidence_level = models.CharField(max_length=10, choices=CONFIDENCE_LEVEL, default='COLD', blank=True, null=True)
estimated_lead_value = models.CharField(max_length=10, choices=LEAD_VALUE, default='1K3K', blank=True, null=True)
estimated_closing_frame = models.CharField(max_length=10, choices=ESTIMATED_CLOSING, default='1-4 Weeks', blank=True, null=True)
def __unicode__(self):
return u" %s - %s " % (self.update, self.updatedate)
Table:
class LeadTable(tables.Table):
business_name = tables.LinkColumn('lead-detail', args=[A('slug')])
updates = tables.Column(accessor='lead.related_update')
class Meta:
model = lead
fields = ("business_name","first_name", "last_name","number_of_pos","submission_date","updates")
attrs = {"class":"paleblue"}
A late answer, but here is what works for me in Django 1.8.6 with django-tables2 1.1.0 (based on Django-Tables2 Issue 156 and This answer). To access a one to many set of objects via a foreign key relation you need to just use the related_name in the accessor and then create a render method to produce what gets written to column cell. In that method you can then get all the foreign model objects and access their fields in a for loop.
class LeadTable(tables.Table):
business_name = tables.LinkColumn('lead-detail', args=[A('slug')])
updates = tables.Column(accessor='related_update')
def render_updates(self, value, table):
updates = ""
uFirst = True
updatesList = list(value.all())
for u in updatesList:
if not uFirst:
updates += ", "
else:
uFirst = False
updates += u.update
return updates
class Meta:
model = lead
fields = ("business_name","first_name", "last_name","number_of_pos","submission_date","updates")
attrs = {"class":"paleblue"}
according to django docs
in your views you can access them in this way (assuming lead_instance is an instance of lead class):
all_leadtables_for_lead = lead_instance.leadtable_set
a side note: use Capitalized names for classes (class Lead(models.Model):) in order to adhere to python PEP8 guidelines.