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

Django自定义save方法规避含3的userprofile_id的潜在弊端咨询

自定义UserProfile ID生成逻辑的潜在弊端咨询

我在Django项目里做了个临时方案:避免生成包含数字3的userprofile_id(比如3、13、203这类),用来临时绕开一个需要耗时解决的问题。我已经写了实现代码,但现在想搞清楚这个临时修复可能存在哪些潜在问题,自己先梳理了几个点,想请大家帮忙判断:

  • User_id与userprofile_id不一致——目前没发现相关问题;
  • 移除自定义方法对数据库完整性的影响——我认为不会产生影响,希望这个判断是对的;
  • 性能问题:保存操作在数据库层面可能有延迟,当前项目处于试点阶段,日均新增用户不会过千。但我疑惑并发注册时会不会出现重复的userprofile_id,以及如何降低死锁风险?

实现代码

class UserProfile(models.Model):
    user = models.OneToOneField(User, null=True, on_delete=models.CASCADE)

    def __str__(self):
        return str(self.user)
    
    def save(self, *args, **kwargs):
        if not self.pk:
            # Logic for generating userprofile_id without '3'
            last_userprofile = UserProfile.objects.all().order_by('-id').first()
            print(f'last_userprofile: {last_userprofile.id}')
            if last_userprofile:
                last_id = last_userprofile.id
                print(f'last_id: {last_id}')
                next_id = last_id + 1
                print(f'next_id: {next_id}')
                while '3' in str(next_id):
                    next_id += 1
                self.id = next_id
            else:
                self.id = 1 

内容的提问来源于stack exchange,提问作者PhilM

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 06:23:12