sql - Django get objects that are foreign key of two models
问题描述
I have the following three models where Budget and Sale both contain a foreign key to Customer:
class Customer(models.Model):
name = models.CharField(max_length=45)
# ...
class Budget(models.Model):
customer = models.ForeignKey(Customer, on_delete=models.PROTECT)
# ...
class Sale(models.Model):
customer = models.ForeignKey(Customer, on_delete=models.PROTECT)
# ...
I want to get a queryset of all Customer objects for which both a Budget and Sale exists. I initially tried getting the intersection of the customer field of all Budget and Sale objects:
customers = {
budget.customer for budget in Budget.objects.all()
} & {
sale.customer for sale in Sale.objects.all()
}
This returns the correct objects, but becomes horribly inefficient as the size of my database grows.
How can I retrieve these objects in a more efficient way? Thanks for any help!
解决方案
推荐阅读
- javascript - Cypress : Setting a variable from the result of a task
- firebase - Firebase 数据库检查 Flutter 的 ListField 中是否存在元素
- c# - 在异常消息中打印 ICollection 中的元素数
- macos - 将 Visual Studio Code 二进制文件添加到 Mac 中的路径,找不到命令,尽管它在 $PATH 中
- apache-spark - 如何在 Spark Dataframe 中像 SQL 一样实现 EXISTS 条件
- php - 如何在 php 中通过 xpath 找到包含特定字符串的元素?
- javascript - 如何在 JS 中将字符串转换为函数原型?
- c# - File.Exist always return false
- javascript - MediaWiki API,波兰字符
- android - “crashlytics 应用初始化程序禁用”是什么意思?