Can I create model in Django without automatic ID?

前端 未结 3 1346
滥情空心
滥情空心 2021-02-07 11:55

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?

I\'m u

相关标签:
3条回答
  • 2021-02-07 12:09

    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).

    0 讨论(0)
  • 2021-02-07 12:16

    You can create a model without an auto-incrementing key, but you cannot create 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).

    0 讨论(0)
  • 2021-02-07 12:28

    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

    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

    thanks everybody

    0 讨论(0)
提交回复
热议问题