Reputation: 8061
My model:
class ClinicPermissions(models.Model):
id = models.AutoField(primary_key=True, unique=True)
clinicid = models.ForeignKey(Clinic, on_delete=models.CASCADE)
doctorid = models.ForeignKey(doctor, on_delete=models.CASCADE)
viewperm_choices = (
(0, 'Cannot view clinic details'),
(1, 'Can view clinic details')
)
viewperms = models.IntegerField(
choices=viewperm_choices, default=0)
editperms_choices = (
(0, 'Cannot edit clinic details'),
(1, 'Can edit clinic details')
)
editperms = models.IntegerField(
choices=editperms_choices, default=0)
editdocs_choices = (
(0, 'Cannot edit doctor details'),
(1, 'Can edit doctor details')
)
editdocs = models.IntegerField(
choices=editdocs_choices, default=0)
class Meta:
unique_together = ["clinicid", "doctorid"]
The above model describes permissions of each doctor in a clinic. I need to get a list of doctor objects associated with a Clinic object, which is stored in ClinicPermissions model, as a queryset and pass it to a form.
i.e
I want to get a specific Clinic.
cl = Clinic.objects.get(id=10)
Then, I want to get a queryset of doctors from the ClinicPermissions, where clinicid = cl:
i.e Something more elegant than the following:
perms = ClinicPermissions.objects.filter(clinicid = cl)
docs = []
for perm in perms:
docs.append(perm.doctorid)
return docs
Here, docs is a list, but I need a queryset, to pass to a form.
Upvotes: 0
Views: 39
Reputation: 88509
Simply
Doctor.objects.filter(clinicpermissions__clinicid_id=10)
Here the value 10
is the PK of Clinic
object
As a side note, In Django, we will not use id
as a suffix to the fields since Django internally handling the same. Similarly, Django handled the Primary field too, hence, no need to define the PK explicitly.
class ClinicPermissions(models.Model):
id = models.AutoField(primary_key=True, unique=True)
clinic = models.ForeignKey(Clinic, on_delete=models.CASCADE)
doctor = models.ForeignKey(Musician, on_delete=models.CASCADE)
# rest of the fields
Upvotes: 4