vivekv
vivekv

Reputation: 2298

How do I make this kind of Query in Django foreign key relationships?

I have the following data model

Customers

Have many Addresses
Have many Credit cards

Given a credit card record, I want to be able find out all the addresses that I can apply against it.

Basically I want to be able to write a query like this...

SELECT address.line1, address.line2, address.city, 
address.state, address.zip FROM 
addresses, creditcards 
WHERE
addresses.custid = creditcards.custid and 
creditcard.number = 'Thenumber#'

I am fairly new to Django and I can only think of writing the code like this which I suspect wil fire 100s of queries.

for acard in creditcard.objects.filter(cardno = 'thenumber#'):
    for anaddress in Address.objects.filter(customer = acard.customer):
        print anaddress.list_values()  

Is there a different design that I should adopt? I cannot think of using ManyToMany here as it is technically not many to many? am I thinking this wrong?

here is the model I had in mind...

class Customer(models.Model):
    pass

class creditcard(models.Model):
    customer = models.ForeignKey(Customer)

class addresss(models.Model):
    customer = models.ForeignKey(Customer)
    line1 = models.CharField()
    # etc., etc., 

Upvotes: 0

Views: 29

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599610

You should always start from the model you want to actually query. In this case, you want addresses, so you should start from there.

addresses = Address.objects.filter(customer__creditcard__number = 'thenumber#')

Upvotes: 3

Related Questions