zinon zinon - 1 year ago 72
Python Question

Django: How to filter patients from one department?

I'm using django v1.8.

I extended the existing User model.


class Institution(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
department = models.CharField(max_length=100)

class Demographic(models.Model):
patient_id = models.IntegerField(unique= True ,primary_key=True)
pub_date = models.DateTimeField(auto_now=True)
author = models.ForeignKey(User)
history = HistoricalRecords()

def __str__(self):
return str(self.patient_id)

I have two users
that belong to the same department and I want both of them to have access to the same patients.

In a template I use a search engine to search patient.

I have this filter:

patient = Demographic.objects.filter(patient_id__icontains=id)

but the 2 users can search only between patients from their departments.

How can I achieve this in filter? What parameter should I include?

Answer Source

A user belongs to a department when he inserts a patient as author then this patient belongs to that department.

So let's get the department of a given user first:

user = request.user # the doctor, the nurse etc
department = Institution.objects.filter(user=user).first().department

Now you want all patients (Demographic instances) where author.institution.department = department

patients = Demographic.objects.filter(author__institution__department=department)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download