ForeignKey (sometimes) not created in a database, constraint missing
|Reported by:||dwich||Owned by:||nobody|
|Component:||Database layer (models, ORM)||Version:||master|
|Severity:||Keywords:||foreign key, constraint, model, database|
|Has patch:||no||Needs documentation:||no|
|Needs tests:||no||Patch needs improvement:||no|
I have this piece of code. Save it as a model definition in a testing django project.
from django.db import models from django.contrib.auth.models import User class Region(models.Model): name = models.CharField(maxlength=128) class ServiceCategory(models.Model): name = models.CharField(maxlength=128) class Service(models.Model): category = models.ManyToManyField(ServiceCategory) name = models.CharField(maxlength=128) class ServiceVariant(models.Model): service = models.ForeignKey(Service) region = models.ForeignKey(Region) name = models.CharField(maxlength=128) class CustomerProfile(models.Model): user = models.ForeignKey(User, unique=True) name = models.CharField(maxlength=64) class BugTest(models.Model): name = models.CharField(maxlength=64)
Then create the database or simply display the SQL using manage.py sqlall myapp and save it. Then comment the last class - BugTest. Recreate the database or show the SQL again and save it. If you diff it, there are two differencies:
- There's no table bugtest in the second SQL dump because there was no definition for it. Which is correct.
- The second difference is probably a bug - there's no constraint for ServiceVariant class refering to Service. The ALTER TABLE myapp_servicevariant ADD CONSTRAINT ... is missing.
I use (freshly exported) django SVN version (and MySQL 5.0.x).