Reputation: 164
I have two models.One of the models has a pk of unique identifying strings. Sometimes it would be something like 'TTL123' and sometimes '000010'. For some reason when I created the foreignkey fields is using integers and the item '000010' shows up as 10. I can't save 'TTL123'. Why has django created the table as integer instead of character field? How do I change it? I've been looking at documentation and can't find answer.
class Item(models.Model):
item_id = models.CharField(max_length=255, primary_key=True)
# ... other fields...
class ItemRestriction(models.Model):
item = models.ForeignKey(Item, related_name='item', on_delete=models.PROTECT, blank=True, null=True)
How can I make the ForeignKey use a character field instead of integer? Now when I try to access item__item_id I get nothing, because it's 000010 in Item table and 10 on ItemRestriction. I don't understand why it's doing this.
Upvotes: 1
Views: 1576
Reputation: 24139
You can use the to_field
.
class ItemRestriction(models.Model):
item = models.ForeignKey(Item, related_name='item', to_field='item_id', on_delete=models.PROTECT, blank=True, null=True)
see: https://docs.djangoproject.com/en/3.0/ref/models/fields/#django.db.models.ForeignKey.to_field
If possible, you might want to consider using an AutoField
or some sort of field that handles unique=True
and auto increments on creation.
Upvotes: 1