Django查找两个孩子的父母

idfiyjo8  于 2023-05-30  发布在  Go
关注(0)|答案(2)|浏览(179)
class Company(models.Model):  
    title = models.CharField()  

class Office(models.Model):  
    сompany = models.ForeignKey(Company, on_delete=models.CASCADE)  
    title = models.CharField()  

class Human(models.Model):  
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    office = models.ManyToManyField(Office)

如何在不使用Prefetch的情况下找到当前用户的公司。因为它很贵

gjmwrych

gjmwrych1#

你可以这样尝试:

>> user = request.user
>> Company.objects.filter(office__human__user=user)

这里我通过Company --> Office --> Human --> User从Company反向查询User。更多信息可以在文档中找到。

ogq8wdun

ogq8wdun2#

Office.objects.filter(humans__user=request.user).select_related('с ompany')

相关问题