You need to enable JavaScript to run this app. 如何在Django中仅为当前实例筛选显示ManyToMany关联对象
优惠活动
大模型
产品
解决方案
定价
更多

如何在Django中仅为当前实例筛选显示ManyToMany关联对象

解决方案

要实现多对多选择控件仅展示当前用户关联的选项,核心是将当前登录的候选人实例传递给表单,再在表单初始化阶段过滤所有多对多字段的可选查询集,修改步骤如下:


1. 修改 forms.py

重写表单的__init__方法,接收传入的候选人实例,逐个过滤多对多字段的可选范围:

from django.forms import ModelForm
from .models import CV, Interet, Langue, Certification, Experience, Competence, Réfférence, DeclarationPerson, Formation

class CVForm(ModelForm) :
    class Meta:
        model=CV
        fields="__all__" 
        exclude = ["candidat"]    

    def __init__(self, *args, candidat=None, **kwargs):
        super().__init__(*args, **kwargs)
        if candidat:
            # 过滤兴趣选项,仅展示当前候选人关联的兴趣
            self.fields['interet'].queryset = Interet.objects.filter(candidat=candidat)
            # 过滤语言选项
            self.fields['Langues'].queryset = Langue.objects.filter(candidat=candidat)
            # 过滤证书选项
            self.fields['Certifications'].queryset = Certification.objects.filter(candidat=candidat)
            # 过滤工作经历选项
            self.fields['Experiences'].queryset = Experience.objects.filter(candidat=candidat)
            # 过滤技能选项
            self.fields['Competence'].queryset = Competence.objects.filter(candidat=candidat)
            # 过滤参考人选项
            self.fields['References'].queryset = Réfférence.objects.filter(candidat=candidat)
            # 过滤个人声明选项
            self.fields['Declaration'].queryset = DeclarationPerson.objects.filter(candidat=candidat)
            # 过滤培训经历选项
            self.fields['Formations'].queryset = Formation.objects.filter(id_candidat=candidat)

注:如果你的Interet/Langue等资源模型和Candidat的关联字段名不是candidat,请替换成你实际的字段名。


2. 修改 views.py

创建表单实例时传入当前登录的候选人实例,同时修正原代码的逻辑错误:

from django.shortcuts import render, redirect
from .forms import CVForm
from .models import Candidat

def createcv(request):
    current_candidat = Candidat.objects.get(id=request.user.candidat.id)
    if request.method=='POST':
        # 提交请求时传入当前候选人用于校验
        cv_form=CVForm(request.POST, candidat=current_candidat)
        if cv_form.is_valid():
            cv_instance = cv_form.save()
            # CV和candidat为多对多关联,手动添加关联关系
            cv_instance.candidat.add(current_candidat)
            return redirect('/resume')
    else:
        # 初始化表单时传入当前候选人,用于过滤可选选项
        cv_form=CVForm(candidat=current_candidat)
    context={'cv_form':cv_form}
    # 替换第二个参数为你实际的模板文件路径
    return render(request, 'create_cv.html', context)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.16 19:36:04