2

I got 3 models

client

loan

installment - one part of loan

shold i do:

loan-foreignKey(client)
installment-foreignKey(loan)

and to get the client installments something like that:

loans = client.loan.all()
result = array()
foreach(loans as loan):
    result = result + loan.installments.all()
return result;

or should I do it like that:

loan-foreignKey(client)
installment-foreignKey(client)
installment-foreignKey(loan)

and just: client.installment.all()

First way seams cleaner from programmer point of view(no spagetti around, no duplicated fields) but I'm worried about performance (you need to search database for all loans then for installments in this loans)

tshepang
  • 12,111
  • 21
  • 91
  • 136
Lord_JABA
  • 2,545
  • 7
  • 31
  • 58

2 Answers2

4

According to Zen of Python: Flat is better than nested. You should think of your models as objects and apply principles of Object Oriented Programming.

Think about the entities you have and and apply the relationships simulating their real life interaction.

"Programs must be written for people to read, and only incidentally for machines to execute."

Paulo Bu
  • 29,294
  • 6
  • 74
  • 73
1

If the client is the same in both models you shouldn't duplicate it. Regarding performance read up on select_related(), only() and defer() in the Django docs.

dan-klasson
  • 13,734
  • 14
  • 63
  • 101