Django获取当前ID以比较两个表在查询集筛选中。

huangapple go评论88阅读模式
英文:

Django get current id to compare two tables in queryset filter

问题

这行代码中的问题在于如何获取“Record form”的当前ID,以将其与“BDC form”的“ref”进行比较,以便填充小部件的结果。您可以使用以下方式来解决这个问题:

queryset=BDC.objects.filter(ref=current_record.id).values_list('model')

这里使用了current_record.id来获取“Record”表单的当前ID,并将其用于过滤BDC对象。

英文:

I'm struggling to achieve a simple queryset filter because i can't find how to get the current id of my form.

view.py

def update_record(request, pk):
    if request.user.is_authenticated:
        current_record = Record.objects.get(id=pk)
        form = AddRecordForm(request.POST or None, instance=current_record)
        if form.is_valid():
            form.save()
            messages.success(request, "Record Has Been Updated!")
            return redirect('home')
        return render(request, 'update_record.html', {'form':form})
    else:
        messages.success(request, "You Must Be Logged In...")
        return redirect('home')

forms.py

class AddRecordForm(forms.ModelForm):
    testrever = forms.ModelMultipleChoiceField(widget=forms.widgets.SelectMultiple, queryset=BDC.objects.filter(ref = ???current.id.of.Record.model???).values_list('model'))

    class Meta:
        model = Record
        exclude = ("user",)



class BDCform(forms.ModelForm):
    ref = forms.CharField(required=False, widget=forms.widgets.TextInput(attrs={"placeholder":"First Name", "class":"form-control"}), label="")
    model = forms.CharField(required=False, widget=forms.widgets.TextInput(attrs={"placeholder":"Last Name", "class":"form-control"}), label="")

    class Meta:
        model = BDC
        exclude = ("user",)

models.py

    class Record(models.Model):
        id = models.CharField(primary_key=True, max_length=50)
        testrever = models.JSONField(max_length=500) 
    
        def __str__(self):
            return (f"{self.first_name} {self.last_name}")

    class BDC(models.Model):
        ref = models.CharField(max_length=50)
        model = models.CharField(max_length=50)

My problem is in this line in forms.py:

queryset=BDC.objects.filter(ref = ???current.id.of.Record.model??? ).values_list('model')

How can i get the current ID of the Record form to compare it with "ref" of BDC form so i can populate the widget with the results ?

Thanks

答案1

得分: 2

你不能在类定义中放置涉及非常量值的查询集。类在模块被导入时定义。

(嗯,有点夸张。你可以将类定义为视图内的内部类,而不是具有模块范围的类。事实上,我甚至不确定为什么这是一个不好的主意,除非是因为我从未见过或尝试过。毕竟,有 forms.modelform_factory。)

你最好的选择是在实例化表单时传递查询集。在表单的 __init__ 中创建子类:

def __init__(self, *args, **kwargs):
    bdcqs = kwargs.pop('bdc_qs', None)         # 获取传递的查询集
    super().__init__(*args, **kwargs) 
    self.fields['testrever'].queryset = bdcqs  # 应用到字段上

在视图中使用:

def update_record(request, pk):
    if request.user.is_authenticated:
        current_record = Record.objects.get(id=pk)
        form = AddRecordForm(request.POST or None, 
            instance=current_record,
            bdc_qs = BDC.objects.filter(
                ref = pk   # 如果我理解问题正确的话
            ).values_list('model', flat=True)
        )
        ...

希望这能帮助你!

英文:

You can't put a queryset involving non-constant values in a class definition. classes get defined when the module is imported.

(Well, slight lie. You could define the class as an inner class inside the view, rather than with module scope. In fact I'm not even sure why it's a bad idea, apart from I've never seen it or tried it. There's forms.modelform_factory, after all).

Your best bet would be to pass the queryset when you instantiate the form. Subclass the form's __init__:

def __init__(self, *args, **kwargs):
    bdcqs = kwargs.pop('bdc_qs', None)         # get the passed queryset
    super().__init__(*args, **kwargs) 
    self.fields['testrever'].queryset = bdcqs  # apply it to the field

and in the view,

def update_record(request, pk):
    if request.user.is_authenticated:
        current_record = Record.objects.get(id=pk)
        form = AddRecordForm(request.POST or None, 
            instance=current_record,
            bdc_qs = BDC.objects.filter(
                ref = pk   # if I understand the question right
            ).values_list('model')
        )
        ...

答案2

得分: 0

这是我为了解决问题所做的:

def __init__(self, *args, **kwargs):
    self.storage_pk = kwargs.pop('pk')
    super(AddRecordForm, self).__init__(*args, **kwargs)
    self.fields['testrever'].queryset = BDC.objects.filter(ref=self.storage_pk).values_list('model', flat=True)

并且修改了:

testrever = forms.ModelMultipleChoiceField(widget=forms.widgets.SelectMultiple, queryset=None)
英文:

this what i did to fix the probleme :

def __init__(self, *args, **kwargs):
    self.storage_pk = kwargs.pop('pk')
    super(AddRecordForm, self).__init__(*args, **kwargs)
    self.fields['testrever'].queryset = BDC.objects.filter(ref=self.storage_pk).values_list('model', flat=True)

and modified

testrever = forms.ModelMultipleChoiceField(widget=forms.widgets.SelectMultiple, queryset=None)

huangapple
  • 本文由 发表于 2023年5月17日 21:27:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/76272638.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定