Python 我可以在没有自动 ID 的情况下在 Django 中创建模型吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28516086/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can I create model in Django without automatic ID?
提问by HQM
I need a table without a primary key (in Django it was created automatically). So my question is: Can I create a model without an ID/primary key?
我需要一个没有主键的表(在 Django 中它是自动创建的)。所以我的问题是:我可以创建一个没有 ID/主键的模型吗?
I'm using Django 1.7.
我正在使用 Django 1.7。
采纳答案by Selcuk
You cancreate a model without an auto-incrementing key, but you cannotcreate one without a primary key.
您可以在没有自动递增键的情况下创建模型,但不能在没有主键的情况下创建模型。
From the Django Documentation:
If Django sees you've explicitly set
Field.primary_key
, it won't add the automatic id column.Each model requires exactly one field to have
primary_key=True
(either explicitly declared or automatically added).
如果 Django 看到您已明确设置
Field.primary_key
,则不会添加自动 id 列。每个模型只需要一个字段
primary_key=True
(显式声明或自动添加)。
回答by catavaran
No, you can't. Excerpt from the documentation:
不,你不能。文档摘录:
Each model requires exactly one field to have primary_key=True (either explicitly declared or automatically added).
每个模型只需要一个字段来具有 primary_key=True (显式声明或自动添加)。
回答by HQM
I've found the solution.
我找到了解决方案。
Since django need Primary Key (either it's composite or single-field ID) so, I've tried to set primary_key=True in every fields in its composite-key combination, and add those fields in Meta and groups in unique_together
由于 django 需要主键(无论是复合 ID 还是单字段 ID),因此,我尝试在其复合键组合中的每个字段中设置 primary_key=True,并将这些字段添加到 Meta 和组中的 unique_together
class ReportPvUv(models.Model):
report_id = models.ForeignKey(Reports, primary_key=True)
rdate = models.DateField(primary_key=True)
fdate = models.DateTimeField(primary_key=True)
ga_pv = models.BigIntegerField()
ga_uv = models.BigIntegerField()
ur_pv = models.BigIntegerField()
ur_uv = models.BigIntegerField()
da_pv = models.BigIntegerField()
da_uv = models.BigIntegerField()
class Meta:
db_table = 'report_pv_uv'
unique_together = ('report_id', 'rdate', 'fdate')
and when I run makemigrations, there are no ID field in it's migrations script :D
当我运行 makemigrations 时,它的迁移脚本中没有 ID 字段:D
thanks everybody
谢谢大家