简体   繁体   中英

How can I get efficiently QuerySet of a Model from another QuerySet without using values or values_list

I have Visit model and Patient model

class Visit(models.Model):
    patient = model.ForeignKey(Patient)
    # other fields

class Patient(models.Model):
    # other fields

I have QuerySet of Visit like this

visits = Visit.objects.filter(#conditions)

How can I get efficiently QuerySet of Patient's instances from the visits QuerySet without using values or values_list. ie

patients_ids = visits.values_list("Patient__id", flat=True).distinct()
patients = Patient.objects.filter(id__in=patients_ids)

It's a bit difficult to understand what you're asking but I think this might be what you want:

visits = Visit.objects.filter(name=somename, count=something)

To get the patients corresponding to that you would do:

patients = Patient.objects.filter(visit__name=somename, visit__count=something).distinct()

Explanation:

The Patient model gets a backwards many-to-one reference called the lower case of the other model by default ( visit in this case). You can then query through that relation using the double underscore feature __ and do the same tests you were going to do in your Visit filter.

Source

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM