Login

Tag "foreign-keys"

Snippet List

Creating MySQL Alter table commands for Foreign Keys

When using mysql the sql that is generated by syncdb doesn't create the foreign key relationship in all cases. This code will run through a file called create_table.sql in which you store all your create sql statements ( use "python manage.py sqlall app1 app2 > create_table.sql" ) and outputs all the neccesary alter table scripts that add the foreign key. Its not 100% proof since the generated names can end up being more than 40 characters. Need to work on that. I have [written](http://vidyanand.wordpress.com/2008/06/16/is-it-a-mysql-or-django-fault/) about it a little more in detail.

  • mysql
  • foreign-keys
Read More

Querying on existence of a relationship

When you have two models joined by a foreign key, it's common to want to retrieve a set of objects from the "target" of the foreign key based on whether there are any objects "pointing" to them. This snippet demonstrates how to do so, using the `extra` method of the default model manager. Note that this is probably more efficient than using two ORM methods (e.g., selecting all values from one table, and using an `id__in` lookup on the other) since it does the whole thing in one query and avoids instantiating any intermediate objects.

  • models
  • orm
  • foreign-keys
Read More

3 snippets posted so far.