Django如何实现用户仅可编辑自身关联Job的userStatus字段
问题分析
你当前的实现存在两个核心问题,完全无法满足需求:
userStatus模型将stage字段设为主键,导致最多只能存储5条对应不同状态的记录,完全没有能力存储「用户+Job」维度的个性化状态Job模型通过外键关联userStatus,意味着单个Job只能绑定唯一的状态记录,所有用户查看同一个Job时拿到的状态完全一致,不可能实现不同用户状态独立的效果
正确实现方案
1. 模型层调整
首先删除Job模型中现有的userStatus外键字段,新建独立的UserJobStatus关联模型,专门用来存储每个用户对应每个Job的专属状态:
from django.db import models from django.contrib.auth.models import User class Job(models.Model): name = models.CharField(max_length=200, help_text='Enter the Spring/Internship') course = models.ForeignKey('Course', on_delete=models.RESTRICT,null=True) company = models.ForeignKey('Company', on_delete=models.RESTRICT,default='N/A') deadline = models.DateField(null=True, blank=True) class UserJobStatus(models.Model): USER_STATUS = ( ('n', 'Not Applied'), ('a', 'Applied'), ('i', 'Got Interview'), ('o', 'Got Offer'), ('r', 'Rejected'), ) user = models.ForeignKey(User, on_delete=models.RESTRICT, related_name="job_statuses") job = models.ForeignKey(Job, on_delete=models.RESTRICT, related_name="user_statuses") stage = models.CharField( max_length=1, choices=USER_STATUS, blank=False, default='n', help_text='What is the current stage of the process', ) class Meta: # 联合唯一约束,保证同一个用户同一个Job只会有一条状态记录,避免重复数据 constraints = [ models.UniqueConstraint(fields=['user', 'job'], name='unique_user_job_status') ]
2. 业务逻辑补充
- 前端展示Job列表/详情时,对当前登录用户,可通过
UserJobStatus.objects.filter(user=当前用户, job=目标Job).first()查询对应状态,无记录时默认返回Not Applied即可 - 状态修改逻辑可以直接用Django自带的
update_or_create方法,自动处理「无记录就新建、有记录就更新」的场景,示例逻辑如下:
# 普通FBV视图修改状态示例 from django.http import JsonResponse from django.contrib.auth.decorators import login_required from .models import Job, UserJobStatus @login_required def update_job_status(request, job_id): if request.method == "POST": new_stage = request.POST.get("stage") # 校验stage参数是否在可选范围内 if new_stage not in [i[0] for i in UserJobStatus.USER_STATUS]: return JsonResponse({"code": 400, "msg": "非法状态值"}) # 更新或创建当前用户对应Job的状态记录 UserJobStatus.objects.update_or_create( user=request.user, job_id=job_id, defaults={"stage": new_stage} ) return JsonResponse({"code": 200, "msg": "状态更新成功"})
3. 权限控制
Job详情页除了用户自身的stage字段开放编辑入口外,其余Job基础字段全部设置为只读,后台接口也不开放普通用户修改Job基础信息的权限即可。
内容的提问来源于stack exchange,提问作者Largecooler21
相关产品推荐
相关产品推荐

