如何在一个查询ORM中连接3个或3个以上的模型



我有4个模型与外键链接

class CustomUser(AbstractUser):
username = None
email = models.EmailField(('email address'), unique=True)
phone_no = models.CharField(max_length=255, unique=True)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []
objects = CustomUserManager()
def __str__(self):
return self.email
class personal_profile(models.Model):
custom_user = models.ForeignKey(CustomUser, on_delete=models.CASCADE)
picture = models.ImageField(default='profile_image/pro.png', upload_to='profile_image', blank=True)
role = models.CharField(max_length=255, blank=True, null=True)
gender = models.CharField(max_length=255, blank=True, null=True)
date_of_birth = models.DateField(blank=True, null=True)
def __str__(self):
return str(self.pk)
class academia_profile(models.Model):
custom_user = models.ForeignKey(CustomUser, on_delete=models.CASCADE)
education_or_certificate = models.CharField(max_length=255, blank=True, null=True)
university = models.CharField(max_length=255, blank=True, null=True)
def __str__(self):
return str(self.pk)
class contact_profile(models.Model):
custom_user = models.ForeignKey(CustomUser, on_delete=models.CASCADE)
country = models.CharField(max_length=255, blank=True, null=True)
state = models.CharField(max_length=255, blank=True, null=True)
city = models.CharField(max_length=255, blank=True, null=True)
def __str__(self):
return str(self.pk)

为了提取这四个模型的数据,我需要通过不同的查询4次来提取它,然后通过将不同的变量传递给HTML模板来提取它——这是一个繁忙的补充,会降低性能速度(我确信!(

我当前的查询类似

user_base = CustomUser.objects.get(id=user_id)
user_personal = personal_profile.objects.get(custom_user=user_id)
academia = academia_profile.objects.get(custom_user=user_id)
contact = contact_profile.objects.get(custom_user=user_id)

通过在ORM中点击一个联接查询,可以在一个变量中获得所有四个查询值吗?

此外,我只想在联接查询中从contact_profile提取country,从personal_profile提取picture

Select_related()可以在这里工作,但如何工作?那是我没有得到的。

您正在寻找预取相关:

返回一个QuerySet,该QuerySet将在单个批次中自动检索每个指定查找的相关对象。

user_base = (
CustomUser
.objects
.prefetch_related(           #<-- THIS!
"personal_profile_set",
"academia_profile_set",
"contact_profile_set")
.get(id=user_id))
personal_profile = user_base.personal_profile_set.all()[0]
academia_profile = user_base.academia_profile_set.all()[0]
contact_profile = user_base.contact_profile_set.all()[0]

顺便说一句,如果每个自定义用户只有一个个人_profile、学院_profile和联系人_profile,请考虑将ForeignKey更改为OneToOneField,并使用select_related。

最新更新