You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Django中为Contiene模型设置num_orden与id_boleto复合主键?

Django中为Contiene模型实现复合主键方案

Django原生不支持复合主键,推荐使用django-composite-keys库来实现,以下是针对你的模型的具体修改步骤:

1. 安装依赖库

pip install django-composite-keys

2. 配置项目settings.py

在INSTALLED_APPS中添加composite_keys:

INSTALLED_APPS = [
    # 其他已有应用
    'composite_keys',
]

3. 修改Contiene模型

将模型继承自CompositeModel,移除原id_boleto字段的primary_key=True参数,然后在Meta类中定义复合主键:

import random
import string
from composite_keys.models import CompositeModel
from django.db import models

class Contiene(CompositeModel):
    id_boleto = models.ForeignKey("Boleto", on_delete=models.CASCADE)
    num_orden = models.ForeignKey("OrdenCompra", on_delete=models.CASCADE)
    boleto_cdg = models.CharField(default='', max_length=50)
    cantidad_total = models.IntegerField()

    class Meta:
        # 定义复合主键为id_boleto和num_orden的组合
        composite_key = ('id_boleto', 'num_orden')

    def generate_random_code(self):
        numbers = ''.join(random.choices(string.digits, k=12))
        letters = ''.join(random.choices(string.ascii_uppercase, k=3))
        return numbers + letters

    def save(self, *args, **kwargs):
        if not self.boleto_cdg:
            self.boleto_cdg = self.generate_random_code()
        super(Contiene, self).save(*args, **kwargs)

    def __str__(self):
        return f"{self.id_boleto} | {self.num_orden} | {self.cantidad_total} | {self.boleto_cdg}"

4. 重新生成迁移并执行

如果之前尝试过其他方案导致迁移出错,建议先清理旧迁移文件(仅保留migrations/__init__.py),再执行以下命令:

# 生成新迁移
python manage.py makemigrations
# 执行迁移
python manage.py migrate

注意事项

  • 若数据库中已有Contiene表的历史数据,需先备份数据,修改主键结构可能导致数据丢失或冲突。
  • 复合主键生效后,id_boleto和num_orden的组合将作为唯一标识,无法创建重复组合的记录。

内容的提问来源于stack exchange,提问作者Hey Mr Dave - HMD

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 00:15:13