Compound/Composite primary/unique key with Django

爱⌒轻易说出口 提交于 2019-12-06 18:45:02

问题


How can you create models (and thus tables) with a compound (composite) primary/unique key using Django?


回答1:


Django does not support compound primary keys. You can create a single compound unique key with Meta.unique_together.




回答2:


if you want only unique mixed fields together use belowcode:

class MyTable(models.Model):
    class Meta:
        unique_together = (('key1', 'key2'),)

    key1 = models.IntegerField()
    key2 = models.IntegerField()

But if you want unique together and one of column be primary, set primary argument for model column, similar below code:

class MyTable(models.Model):
    class Meta:
        unique_together = (('key1', 'key2'),)

    key1 = models.IntegerField(primary_key=True)
    key2 = models.IntegerField()



回答3:


A composite key consists of more than one attribute to uniquely identify an entity occurrence. This differs from a compound key in that one or more of the attributes, which make up the key, are not simple keys in their own right.

For example, you have a database holding your CD collection. One of the entities is called tracks, which holds details of the tracks on a CD. This has a composite key of CD name, track number.



来源:https://stackoverflow.com/questions/2270808/compound-composite-primary-unique-key-with-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!