Django:将 url slugs 传递给 formset 查询集

Django: Passing url slugs to formset queryset

我正在尝试 change the queryset 我的表单集 'alternative approach':

Alternatively, you can create a subclass that sets self.queryset in init:

from django.forms import BaseModelFormSet from myapp.models import Author

class BaseAuthorFormSet(BaseModelFormSet):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.queryset = Author.objects.filter(name__startswith='O')

现在我的问题是,我必须将变量传递到这个查询集中。因此,我尝试像这样调整 forms.py 中的 BaseAuthorFormSet:

class BaseAssignAttendeeFormSet(BaseModelFormSet):

    def __init__(self, order_reference, access_key, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.queryset = Attendee.objects.filter(
            order__order_reference=order_reference,
            order__access_key=access_key,
        )

我在 views.py 中的 function-based-view 是这样开始的:def assign_attendee(request, order_reference, access_key): order_referenceaccess_key 是来自 url 的鼻涕虫。

有谁知道将这两个传递到我的查询集的方法吗?

您可以在视图中的表单集初始化期间传递参数:

MyFormSet = modelformset_factory(MyModel, fields=('name', 'title'), formset=BaseAssignAttendeeFormSet)
formset = MyFormSet(order_reference, access_key, #Other orguments here)

在 formset 中你需要调用超类的 __init__ 方法:

class BaseAssignAttendeeFormSet(BaseModelFormSet):

    def __init__(self, order_reference, access_key, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.queryset = Attendee.objects.filter(
            order__order_reference=order_reference,
            order__access_key=access_key,
        )