inspectdb and foreign keys

711 views
Skip to first unread message

mthorley

unread,
Apr 2, 2008, 6:12:07 PM4/2/08
to Django users
Greetings, I used inspectdb to create my models and then tried editing
the generated models in order to define the ForeignKey relationships,
and I'm getting an error.

Here's what I have. Note: I commented out the original category field
and tried adding my own ForeignKey

class MdlCourseCategories(models.Model):
id = models.IntegerField(primary_key=True)
name = models.CharField(max_length=765)
description = models.TextField(blank=True)
parent = models.IntegerField()

class Meta:
db_table = u'mdl_course_categories'

class MdlCourse(models.Model):
id = models.IntegerField(primary_key=True)
#category = models.IntegerField()
category = models.ForeignKey(MdlCourseCategories, to_field='id')
sortorder = models.IntegerField()
password = models.CharField(max_length=150)
fullname = models.CharField(max_length=762)
shortname = models.CharField(max_length=300)

class Meta:
db_table = u'mdl_course'

Using these models I do the following in the manage.py shell

>>> from cca.moodle.models import *
>>> cs = MdlCourse.objects.all()
>>> cs
OperationalError: (1054, "Unknown column 'mdl_course.category_id' in
'field list'")

to_field doesn't work quite like I expected. Does anyone know a way to
make models.ForeignKey to at a specific table.column?

Humblest Thanks and Kind Regards
--
matthew

carole...@gmail.com

unread,
Apr 3, 2008, 12:05:16 AM4/3/08
to Django users
In your database ( not in the model ) rename the field 'category in
table MdlCourse to category_id and it should fix the problem...
normally a ForeignKey field name in the database is ClassName_id

Karen Tracey

unread,
Apr 3, 2008, 12:29:49 AM4/3/08
to django...@googlegroups.com
On Thu, Apr 3, 2008 at 12:05 AM, carole...@gmail.com <carole...@gmail.com> wrote:

In your database ( not in the model ) rename the field 'category in
table MdlCourse to category_id and it should fix the problem...
normally a ForeignKey field name in the database is ClassName_id

Or, if you do not want to change your database column name, you can tell Django what it is by passing db_column='category' as an argument on the ForeignKey definition for category.  Note the to_field argument is not needed here, by default the to_field is assumed to be the target model's primary key, and that is what you are using.

Karen

mthorley

unread,
Apr 3, 2008, 10:39:36 AM4/3/08
to Django users
Thanks so much Karen, that is exactly what I needed!

On Apr 2, 10:29 pm, "Karen Tracey" <kmtra...@gmail.com> wrote:
> On Thu, Apr 3, 2008 at 12:05 AM, carole.zie...@gmail.com <
Reply all
Reply to author
Forward
0 new messages