Using a UUID as a primary key in Django models (generic relations impact)

前端 未结 6 737
旧巷少年郎
旧巷少年郎 2020-12-02 06:52

For a number of reasons^, I\'d like to use a UUID as a primary key in some of my Django models. If I do so, will I still be able to use outside apps like \"contrib.comments\

6条回答
  •  再見小時候
    2020-12-02 07:29

    I ran into a similar situation and found out in the official Django documentation, that the object_id doesn't have to be of the same type as the primary_key of the related model. For example, if you want your generic relationship to be valid for both IntegerField and CharField id's, just set your object_id to be a CharField. Since integers can coerce into strings it'll be fine. Same goes for UUIDField.

    Example:

    class Vote(models.Model):
        user         = models.ForeignKey(User)
        content_type = models.ForeignKey(ContentType)
        object_id    = models.CharField(max_length=50) # <<-- This line was modified 
        object       = generic.GenericForeignKey('content_type', 'object_id')
        vote         = models.SmallIntegerField(choices=SCORES)
    

提交回复
热议问题