如何在不使用值或values_list的情况下从另一个QuerySet有效地获得Model的QuerySet

时间:2021-08-28 21:27:28

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

我有像这样的访问QuerySet

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. i.e.

如何在不使用值或values_list的情况下从访问QuerySet中有效地获取患者实例的QuerySet。即

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

1 个解决方案

#1


0  

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.

Patient模型默认获得一个倒向的多对一参考,称为另一个模型的小写(在这种情况下访问)。然后,您可以使用双下划线功能__查询该关系,并执行您在访问过滤器中要执行的相同测试。

Source

#1


0  

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.

Patient模型默认获得一个倒向的多对一参考,称为另一个模型的小写(在这种情况下访问)。然后,您可以使用双下划线功能__查询该关系,并执行您在访问过滤器中要执行的相同测试。

Source