saran
saran

Reputation: 378

Error: Cannot resolve keyword 'id' into field

class Profile(models.Model):
    name=models.CharField(max_length=20, primary_key=True )
    age=models.IntegerField()

    def __str__(self):
        return self.name

class Like(models.Model):
    user=models.ForeignKey(Profile,on_delete=models.CASCADE)
    choice_text = models.CharField(max_length=200)
    like=models.IntegerField(default=0)

    def __str__(self):
        return self.choice_text

in python manage.py shell command:

    from database.models import Profile, Like 
    p=Profile(name='test', age=66)
    p.save()
    p.id

AttributeError                            Traceback (most recent call last)
<ipython-input-35-25ec00f2e4bf> in <module>
----> 1 p.id

But if you follow the example on www.djangoproject.com , you will get to see result of p.id is 1.

Any help will be appreciated to understand the databases as I never worked on the databases.

Upvotes: 1

Views: 4079

Answers (2)

ShaileshKumarMPatel
ShaileshKumarMPatel

Reputation: 153

This message is also found when primary key in database is not called "id"
It must be up to user to name primary key (particularly if database is old)
Following model definition gives error
examination_id=models.AutoField(primary_key=True)
Following model definition corrects error without change in database PK
id = models.AutoField(primary_key=True,db_column='examination_id')
Note that django is happy with "id", mysql is free with whatever primary key is named.
In this scenario, if examination_id is used as foreign key in another table, there is further complication. Now, django want "examination_id_id" field in referenced table.
This message can be solved by defining foreign key in referred table as follows
examination_id = models.ForeignKey(Examination, models.DO_NOTHING, db_column='examination_id')

Upvotes: 0

wfehr
wfehr

Reputation: 2225

You model has the primary_key field name.

So if you save() your model it won't have a field called id as this is a default primary_key-field if you didn't define any.

You can access the primary_key by obj.pk (or obj.name in your case).

Upvotes: 6

Related Questions