Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access Foreign key models with custom primary key in django

These are my two models:

In models.py

class Person(models.Model):

    person_no = models.IntegerField(max_length=10, primary_key='True')
    phone = models.IntegerField(max_length=20)

    class Meta:
        db_table = 'person'

class person_ext(models.Model):

    person_no = models.ForeignKey(Person)
    key = models.CharField(max_length=64)
    value = models.TextField()

    class Meta:
        db_table = 'personExt'

I went to manage.py shell to test my model and I tried to access the cell_phone of a person given the person's id this way:

        p = Person.objects.get(pk=1)
        cell_phone = Person_ext.objects.get(person_no=p).filter(key='cell').value

However, I'm getting the following error:

DatabaseError: (1054, "Unknown column 'personExt.person_no_id' in 'field list'")

My database column is just "person_id" but django is looking for "person_no_id". What do I have to do to access the personExt data using a person_no from person.

like image 600
Sapphire Avatar asked Dec 16 '12 02:12

Sapphire


1 Answers

person_no_id is what I would expect for Django to look at. It appears that your database is actually out of sync with what your models expect. I would consider comparing the output of (sql)

SHOW CREATE TABLE `personExt `;

and

python manage.py sql APPNAME

for the table in question. You can fix this problem by using migration tools like south, recreating the database, or manually editing the database to fix the field. Alternatively you can change the model if you're importing:

person_no = models.ForeignKey(Person, db_column="person_id")

Edit: primary_key should be True, not the string "True," Indentation looks wrong for the Meta class and you should consider naming person_ext as PersonExt instead.

like image 167
Aea Avatar answered Nov 15 '22 08:11

Aea