Django将ForeignKey保存为字符而不是整数字段

问题描述

我有两个模型,其中一个模型有一个唯一的识别字符串pk。有时会是“ TTL123”,有时会是“ 000010”。由于某些原因,当我创建外键字段时使用整数,并且项“ 000010”显示为10。我无法保存“ TTL123”。 django为什么将表创建为整数而不是字符字段?我该如何更改?我一直在查看文档,但找不到答案。

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)

如何使ForeignKey使用字符字段而不是整数?现在,当我尝试访问item__item_id时,我什么也没得到,因为它在Item表中为000010,在ItemRestriction中为10。我不明白为什么要这么做。

解决方法

您可以使用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)

请参阅:https://docs.djangoproject.com/en/3.0/ref/models/fields/#django.db.models.ForeignKey.to_field

如果可能,您可能要考虑使用AutoField或某种处理unique=True并在创建时自动递增的字段。