[Answer]-Duplicated queries in CreateView

1👍

Repeated queries can be python properties:

@property
def meta(self):
    return get_object_or_404(MetasSPE, pk=self.kwargs['pk'])

@property
def pipol(self):
    return Pipol.objects.filter(puesto=self.meta.puesto)
👤lukkol

0👍

Thanks @lukkol

Also, I removed teh get_initial() to keep only one function, so this is teh class now:

class CrearEvidencia(CreateView):
    model = Evidencia
    form_class = EvidenciaForm
    template_name_suffix = '_add'

    @property
    def meta(self):
        return get_object_or_404(MetasSPE, pk=self.kwargs['pk'])

    @property
    def pipol(self):
        return Pipol.objects.filter(puesto=self.meta.puesto)

    def get_form(self, form_class):
        form = super(CrearEvidencia, self).get_form(form_class)
        form.fields['miembro'].queryset = self.pipol
        form.fields['meta'].initial = self.meta
        return form

Leave a comment