Django自定义主键 [英] Django Custom primary key
问题描述
当我检查Trac数据库时,我得到:
When I inspect the Trac database I get:
class TicketChange(models.Model):
ticket = models.IntegerField()
time = models.BigIntegerField()
author = models.TextField(blank=True)
field = models.TextField()
oldvalue = models.TextField(blank=True)
newvalue = models.TextField(blank=True)
class Meta:
managed = False
db_table = 'ticket_change'
没有主键:
>>> TicketChange.objects.all()
DatabaseError: column ticket_change.id does not exist
LINE 1: SELECT "ticket_change"."id", "ticket_change"."ticket", "tick...
因为我需要指定一个pk,但是Trac中 ticket_change
的原始主键是:
Because I need to specify a pk but the original primary key of ticket_change
in Trac is:
Primary key (ticket, time, field)
但是在Django中是不可能的: Django多列主键讨论.
But It's not possible in Django: Django Multi-Column Primary Key Discussion.
如果我像pk那样定义 time
,则无法同时添加两个票证更改.
If I define time
like pk I can't add two tickets changes in the same time.
我该怎么办?
推荐答案
您是对的.这是一个已知的问题.因此,唯一的解决方案是骇客(之类).
You're right. It's a known problem. So the only solutions are hacks (sort of).
您最好的选择是使用 django-compositepks .缺点是它实际上并不支持模型关系,因此您将无法从Composite-pk模型导航到任何关系.但是,查看您的TicketChange模型似乎不是问题(除非您有更多与此模型相关的模型).
Your best option is to use django-compositepks. The drawbacks are that it doesn't really support model relationships, so you will not be able to navigate to any relationship from your composite-pk model. However, looking at your TicketChange model this doesn't seem like an issue (unless you have more models with relationships to this one).
另一种选择是手动添加id列(并确保对数据库应用所有其他更改),从而创建新的单列主键.第三种选择(以及我可能会做的)与最后一种选择非常相似,但是更简洁,它是从头开始创建一个新数据库,然后通过从现有旧数据库中获取数据来用脚本填充该数据库.
Another option would be to manually add the id column (and make sure to apply any additional changes to the db), thereby creating the new one-column primary key. A third option (and what I would probably do), pretty similar to the last one but cleaner, would be to create a new database from scratch and then populate it with a script by fetching the data from your existing legacy db.
对不起,我没有适合您的更好的解决方案,事实就是这样.旧版dbs和django总是让人头疼,我自己也经历了一些类似的过程.希望这会有所帮助!
Sorry I don't have any better solution for you, that's the way it is. Legacy dbs and django are always a headache, have gone through some similar processes myself. Hope this helps!
这篇关于Django自定义主键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!