我在查询反向关系时遇到了麻烦,我学了很多关于
首先看一下我的模型:
我正在尝试过滤“Person”模型,以检查这个人是否有任何“处方”,“销售”和“预约”,我想要用一个单一的查询来获取所有这些信息。将使用人的“别名”(主键)来过滤它。
我可以像下面这样分别进行过滤:
但我不想这样做,因为它会有性能问题。我不想用单独的查询方式。
我只想查询
例如:
非常感谢!
select_related
和prefetch_related
的知识,但我仍然没能实现这个功能。首先看一下我的模型:
from django.db import models
import uuid
class Person(models.Model):
alias = models.UUIDField(primary_key=True,default=uuid.uuid4, editable=False, unique=True)
name = models.CharField(max_length=20)
class Appointment(models.Model):
patient = models.ForeignKey(Person, related_name="patient_for_appointment", on_delete=models.CASCADE)
data = models.CharField(max_length=20)
class Sales(models.Model):
customer = models.ForeignKey(Person, related_name="customer_for_sales", on_delete=models.CASCADE)
amount = models.FloatField()
class Prescription(models.Model):
patient = models.ForeignKey(Person, related_name="Patient_for_prescription", on_delete=models.CASCADE)
details = models.CharField(max_length=100)
我正在尝试过滤“Person”模型,以检查这个人是否有任何“处方”,“销售”和“预约”,我想要用一个单一的查询来获取所有这些信息。将使用人的“别名”(主键)来过滤它。
我可以像下面这样分别进行过滤:
patient_alias = '53fsdfsdf-fdsfds-df-fdf'
queryset = Appointment.objects.filter(
patient__alias=patient_alias
)
但我不想这样做,因为它会有性能问题。我不想用单独的查询方式。
我只想查询
Person
模型,以检查一个人是否有预约、处方或销售。例如:
Person.objects.filter(alias='某人的别名')
请问有谁可以帮助我实现这个功能?非常感谢!
.prefetch_related(..)
部分,例如Person.objects.filter( patient_for_appointment__isnull=False ).union( Person.objects.filter(customer_for_sales__isnull=False), Person.objects.filter(Patient_for_prescription__isnull=False) ).prefetch_related('patient_for_appointment', 'patient_for_prescription', 'customer_for_sales')
。但这样会产生额外的查询。但是在这里并不是坏事,实际上,在一对多关系中查询并在一个查询中获取它可能会导致网络拥塞重复。 - Willem Van Onsem