Hacker News new | ask | show | jobs
by icn2 4301 days ago
I haven't followed django for a while. Could someone explain a bit more about django' model association part. Is it currently comparable to rails's model associations? Looking at these two pages http://guides.rubyonrails.org/association_basics.html https://docs.djangoproject.com/en/dev/ref/models/relations/

It seems there are a bit more on rails model associations.

2 comments

You want this page:

https://docs.djangoproject.com/en/1.7/ref/models/fields/#mod...

In general:

Django's ForeignKey is equivalent to Rails' belongs_to.

Django's OneToOneField is equivalent to Rails' has_one.

Django's ManyToManyField is equivalent to Rails' has_and_belongs_to_many.

Also, in Django one generally only declares the relationship from one "side", unlike Rails where the relationship is declared on both "sides" (i.e., in Django one simply sets up a ForeignKey on A pointing to B, rather than placing relationship identifiers on both A and B).

The equivalent of ":through" is also available.

Django has GenericForeignKey as an equivalent to Rails' polymorphic associations.

Just to clarify a little:

> Also, in Django one generally only declares the relationship from one "side", unlike Rails where the relationship is declared on both "sides" (i.e., in Django one simply sets up a ForeignKey on A pointing to B, rather than placing relationship identifiers on both A and B).

That's because django will automatically add the reverse of the relation to B, so that you can access A through B. You can disable that functionality optionally though.

Isn't Rails getting real foreign keys only in yet to release 4.2?
Not using proper foreign keys doesn't mean you can't have associations, it just means that the database won't enforce their integrity. (If you wanted that enforcement in rails, the traditional solution was the Foreigner gem[0]).

(My guess is Rails didn't use proper FKs by default because the default development db (SQLite) originally didn't support foreign keys (though it has for a while now, since 3.9.16), and they presumably wanted to minimise the differences in the way they use different databases).

[0] https://github.com/matthuhiggins/foreigner