A
A
Andrew2020-04-23 16:31:56
Django
Andrew, 2020-04-23 16:31:56

How to remove duplicate requests when calling a form?

Good afternoon. I figured out how to use select_related and prefetch_related when displaying data.
How can I do the same when submitting a form?
For example:

class Project(models.Model):
    name = models.CharField(max_length=1024)
    short_name = models.CharField(max_length=128, unique=True)
    address = models.TextField(blank=True)
    client = models.ForeignKey(Supplier, related_name='client', on_delete=models.PROTECT)
    client_contact = models.ForeignKey(SupplierContact, related_name='client_contact', on_delete=models.PROTECT, blank=True, null=True)
    contractor = models.ForeignKey(Supplier, related_name='contractor', on_delete=models.PROTECT)
    contractor_contact = models.ForeignKey(SupplierContact, related_name='contractor_contact', on_delete=models.PROTECT, blank=True, null=True)
    inspector = models.ForeignKey(Supplier, related_name='inspector', on_delete=models.PROTECT, blank=True, null=True)
    inspector_contact = models.ForeignKey(SupplierContact, related_name='inspector_contact', on_delete=models.PROTECT, blank=True, null=True)


The form:
class ProjectForm(forms.ModelForm):
    
    class Meta:
        model = Project
        fields = [
            'name', 'short_name', 'address', 'client', 'client_contact', 'contractor', 'contractor_contact', 
            'inspector', 'inspector_contact']
        widgets = {
            'name': forms.TextInput(attrs={'class': 'form-control'}),
            'short_name': forms.TextInput(attrs={'class': 'form-control'}),
            'address': forms.TextInput(attrs={'class': 'form-control'}),
            'client': forms.Select(attrs={'class': 'form-control'}),
            'client_contact': forms.Select(attrs={'class': 'form-control'}), 
            'contractor': forms.Select(attrs={'class': 'form-control'}),
            'contractor_contact': forms.Select(attrs={'class': 'form-control'}), 
            'inspector': forms.Select(attrs={'class': 'form-control'}),
            'inspector_contact': forms.Select(attrs={'class': 'form-control'}),


When displaying the form, respectively, I have 6 queries in the database, instead of 2 (or rather, even instead of one).

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dr. Bacon, 2020-04-23
@G_r_i_n_v_i_c_h

Select_related will not help here, since these are requests for options for field values ​​for each ForeignKey, I don’t see much point in removing them, but if you really want to, then rather through queryset overrides for each ForeignKey field in __init__ in ProjectForm.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question