views:

53

answers:

3

This is an extremely naive question. As you can tell, it comes from someone who doesn't know much about either databases or Django.

What are the advantages of using ForeignKeys in Django?

Maybe an example will help me understand better. I have tables like this already:

City:
    id = IntegerField() # e.g. 15
    name = CharField() # e.g. 'Rome'    
Country:
    name = CharField() e.g. 'Italy'
    capital = IntegerField() # e.g 15

Should I bother changing capital to ForeignKey(City), and if so, why? Do certain things become quicker, more convenient, or otherwise better?

thanks!

+4  A: 

Foreign keys are constraints on your data model that allow you to ensure consistency. Basically, in your example, if you didn't have capital as a ForeignKey to a City it could potentially contain an id of a City that didn't exist! When you use ForeignKey instead, it places a constraint on the database so that you cannot remove things that are currently referenced by other things. So if you tried to delete the City named "Rome" before deleting the Country named "Italy" who has that city as its capital, it wouldn't allow you to.

Using ForeignKey instead would make sure you never had to worry about whether or not the "thing" on the other end of the relationship was still there or not.

Daniel DiPaolo
+1  A: 

Using ForeignKeys enables Django to "know" about the relations. So you can follow the relations without taking care about how they are stored, eg you can do the following without having to care how the relation is stored:

country = Country.objects.get(pk=1)
print country.capital.name
italy = Country.objects.get(capital__name="Rome")

Also for keeping constraints Django will follow the relations when deleting objects that are referenced by a ForeignKey. Django also keeps track of the reverse relationships (without needing to explicitly define them), so you can do something like countries = rome.country_set.all() (which makes not so much sense in this example, since it would make more sense to use a OneToOneField here...

lazerscience
A: 

Referential integrity. OTOH it is quite possible to have a database that neither knows nor cares about FKs - in fact I work with a legacy db like this at work.

jambox