Reputation: 187
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.
Upvotes: 0
Views: 1266
Reputation: 1
I would recommend the use of a uuid as your primary key. Solves your unique problem, obfuscates your pk, is unique across the universe, and is built into django as well.
Since you mentioned slug, there are ways to have a unique slug per model where you'd never need to make a composite key with the pk. Or, you can include the slug in the url for cosmetic reasons and just filter in your view for only the pk, which should always be unique.
But ordinarily, having the same pk in two models shouldn't really ever be an issue, and without knowing more, I would be concerned you're doing something odd.
Upvotes: 0
Reputation: 223
Define id as an IntegerField instead of auto. Voice always has even numbers as id and Group always odd. This way you will even know in advance in which model you should look for
Upvotes: 0
Reputation: 13731
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
Upvotes: 2