【问题标题】:Django: How to make Id unique between 2 different model classesDjango:如何使 Id 在 2 个不同的模型类之间唯一
【发布时间】:2021-06-20 08:23:49
【问题描述】:

我正在解决一个需要 2 个不同模型具有唯一 ID 的问题。因此,ModelA 的实例永远不应与 ModelB 实例具有相同的 id。

例如,确保这两种模型类型不会有重叠 ID 的 Django 方法是什么?

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


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

编辑 1:

这是我所做的一个例子,它有效,但感觉不正确。我应该从具体的基类继承吗?

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)

【问题讨论】:

  • 你有任何代码你试图呈现?很高兴展示您尝试过的内容和所拥有的内容,这样人们就可以开始研究解决方案(如果是这样的话)。无论如何:你有这些模型的构造函数吗?提供更多关于类的上下文可能会很好。使用构造函数,您可以在创建新条目之前查询以从其他模型中使用 ids
  • Matheus 见编辑 1
  • 对于一个 UUID 字段,我应该关注性能吗? stackoverflow.com/questions/3936182/….
  • 取决于您的规格。根据您链接的问题的答案,您还可以使用另一个值作为主键,并且仍然保留 UUIDField 的唯一 ID,对性能影响较小。

标签: python django


【解决方案1】:

正如Vishal Singh 所评论的,Django 的Model 中的UUIDField 类可用于创建

用于存储通用唯一标识符的字段。

正如提到的here

用法如下:

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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-31
    • 1970-01-01
    • 1970-01-01
    • 2012-09-25
    • 1970-01-01
    相关资源
    最近更新 更多