首页 > 解决方案 > 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!

标签: sqldjango

解决方案



推荐阅读