查找Django中由两个子项确定的父项

huangapple go评论63阅读模式
英文:

Django Find parent by two children

问题

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

英文:
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)

how to find current user's company without using Prefetch. Because it's expensive

答案1

得分: 1

你可以尝试像这样操作:

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

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

英文:

You can try like this:

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

Here I am reverse querying User from Company via Company --> Office --> Human --> User. More information can be found in the documentation.

答案2

得分: 0

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

英文:

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

huangapple
  • 本文由 发表于 2023年5月24日 20:39:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/76323639.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定