Fry
Fry

Reputation: 73

Django: How to make Id unique between 2 different model classes

Im working on a problem that requires 2 different models to have unique Ids. So that an instance of ModelA should never have the same id as a ModelB instance.

For example, What would be the Django way of making sure these two model types wont have overlapping Ids?

class Customer(models.Model):
    name = models.CharField(max_length=255)


class OnlineCustomer(models.Model):
    name = models.CharField(max_length=255)

Edit 1:

Here is an example of something that I've done that works, but does not feel correct. Should I be inheriting from a concrete base class?

class UniqueID(models.Model):
    pass


def create_unique_id():
    try:
        UniqueID = UniqueID.objects.create()
    except:
        # This try except is here to allow migration to pass since Customers need access to this function during migration
        # This should never happen
        return 0
    return UniqueID.id

class Customer(models.Model):
    id = models.IntegerField(primary_key=True, default=create_unique_id)

class OnlineCustomer(models.Model):
    id = models.IntegerField(primary_key=True, default=create_unique_id)

Upvotes: 1

Views: 1199

Answers (1)

MatBBastos
MatBBastos

Reputation: 401

As Vishal Singh commented, the UUIDField class from Django's Model can be used to create

A field for storing universally unique identifiers.

As mentioned here.

Usage could be as following:

import uuid
from django.db import models


class Customer(models.Model):
    id_ = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    name = models.CharField(max_length=255)


class OnlineCustomer(models.Model):
    id_ = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    name = models.CharField(max_length=255)

Upvotes: 1

Related Questions