tklodd
tklodd

Reputation: 1079

How to handle Many-to-Many Relation in Django without an Intermediary Table?

I have inherited a weird table structure:

class Customer(models.Model):
    account_number = models.CharField()

class Subscription(models.Model):
    account_number = models.CharField()

So the Customer and Subscription models are linked by their account numbers. Each customer can have multiple subscriptions, and each subscription can have multiple customers, but there is no intermediary table; there is no "Account" table. How do I handle this sort of thing? If I have a Subscription queryset, how do I go about getting the corresponding Customer queryset without doing a horribly long query like

customers = Customer.objects.filter(account_number__in=list(subscriptions.values_list('account_number', flat=True)))

I'm trying to avoid this because it would generate a massive query that would take a very long time to execute.

Upvotes: 1

Views: 122

Answers (1)

Du D.
Du D.

Reputation: 5310

Because it doesn't have a m2m table, that is probably the best way to do it. However, you can optimize the query a bit to leverage Django to use subquery instead of a list of account numbers in the where statement.

subs = subscriptions.only('account_number').all()
customers = Customer.objects.filter(account_number__in=subs) 

# if you print out the query you should see a subquery in the query where statement
print(customers.query)

Upvotes: 1

Related Questions