Search code examples
pythondjangodjango-modelsuuid

Django: Unique ID's across tables


I was curious if there was a good solution to implement unique ID's between tables.

class Voice(models.Model):
    id = ..          <------|
    slug = ...              |
    name = ....             |-- No duplicate IDs
                            |
class Group(models.Model):  |
    id = ..          <------|
    slug = ...
    name = ....

My hope is that when I get an ID in a view, selecting from one model will give me None but the other will always return the object (and vice versa). If there is a better approach feel free to share. Right now I am using the slug+id as query filters but would like to move away from that.


Solution

  • I'd worry less about the unique ids and consider the data model relationships. From what you're saying, it sounds like there's a commonality between the two and that model can have a voice, group or both associated with it.

    class NewCommonModel(models.Model):
        # common fields go here.
    
    class Voice(models.Model):
        new_common_model = models.OneToOneField(NewCommonModel, on_delete=models.CASCADE)
        # voice specific fields
    
    
    class Group(models.Model):
        new_common_model = models.OneToOneField(NewCommonModel, on_delete=models.CASCADE)
        # group specific fields