【发布时间】:2020-01-02 23:20:15
【问题描述】:
我在查询反向关系时遇到了麻烦,我学到了很多关于 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 模型以检查此人是否有任何 prescription、sales 和 appointment 我想通过像此人这样的单个查询来获取所有这些。将用alias(主键)的人过滤它
我可以用单独的查询过滤它,比如
patient_alias = '53fsdfsdf-fdsfds-df-fdf'
queryset = Appointment.objects.filter(
patient__alias=patient_alias
)
但我不想要这个,因为它有性能问题。我不希望这个单独的查询。
我只想查询Person 模型来检查一个人是否有约会、处方或销售
点赞Person.objects.filter(alias='a person alias)
谁能帮我实现这个目标?
非常感谢
【问题讨论】:
标签: django django-models django-queryset django-orm