英文:
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')
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论