目前,这是我在models.py中拥有的:
class Campaign(models.Model):
campaign_id = UUIDField(auto=True)
name = models.CharField("Campaign Name", max_length=255)
class CampaignResponse(models.Model):
campaign = models.ForeignKey(Campaign)
user = models.EmailField("Email", max_length=200)
response = models.TextField()
最近,我正在考虑将Campaign模型中的campaign_id从
UUIDField
更改为CharField
,但是当我尝试这样做时,我注意到campaign_id的数据正在更改(例如,当,但现在将其转换为"7182c679f72844ca83c9648a120bb066"
后变为UUIDField
。我需要执行一些步骤,以便可以在不更改数据的情况下将
"7182c679-f728-44ca-83c9-648a120bb066"
转换为CharField
并确保Campaign和UUIDField
之间的关系不中断吗? 最佳答案
campaign_id不是模型Campaign的主键。但这可能是最好的,因为现在将UUID转换为CharField时,您的关系不会中断。
首先制作campaign_id CharField
campaign_id = models.CharField(max_length=36, ) # add other stuff too which you want like unique etc.
关于从uuid转换为str,打开shell
py manage.py shell
并运行以下命令:from myApp.models import Campaign
for c in Campaign.objects.all():
c.campaign_id = str(c.campaign_id).replace('-', '')
检查您的数据库以确保其正常工作。现在,您可以将CharField的
max_length
减小为32,因为campaign_id中所有多余的破折号(-
)都消失了。仅因为字段是UUID并不意味着它就是主键。要使字段成为主键,您需要传递
primary_key=True
。您可以像这样进行主键id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
关于python - 将UUIDField转换为CharField,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52511804/