Duplicate request when displaying a form associated with the Django model

I am displaying the SendRnxForm form on the Django website. The form is linked to the FilesData model and displays a drop-down list -

class SendRnxForm(forms.ModelForm):
    class Meta:
        model = FilesData
        fields = ['el_type',]
        widgets = {
            'el_type': forms.Select(attrs={'class': 'form-select', 'id': 'elTypeId'}),
        }
class FilesData(models.Model):
    el_type = models.ForeignKey(ElType,  blank=False,  default='1',  on_delete=models.DO_NOTHING, related_name='files', verbose_name="Types el")

The drop-down list should contain all records of the linked table, and the first record is selected by default. FilesData is associated with the model -

class ElType(models.Model):
    name = models.CharField(max_length=16, db_index=True, verbose_name="Types el")
    slug = models.SlugField(max_length=24, unique=True, db_index=True, verbose_name="Код")

    def __str__(self):
        return self.name

In this case, the request to get data from the database is duplicated

SELECT `dashApp_cordtype`.`id`,
       `dashApp_cordtype`.`name`,
       `dashApp_cordtype`.`slug`
  FROM `dashApp_cordtype`
 ORDER BY `dashApp_cordtype`.`id` ASC

Views is based on CreateView:

class dashForm(DataMixin, CreateView):
    form_class = SendRnxForm
    template_name = 'dashApp/dash.html'
    success_url = reverse_lazy('home')

How can I get rid of duplicate requests in this case?

I can't figure out where to use select_related/prefetch_related

def get_queryset(self):
    queryset = FilesData.objects.select_related('el_type').all()
    return queryset

you can use get_queryset method for custom use of select related.

Back to Top