0

inlineformset_factory` with 50 extra rows. It is taking forever to load and getting 204 queries are running to get that data with almost 200 duplicate queries

Here are my models

class Item_type(models.Model):
    title = models.CharField(max_length=100, null=True)
    alias = models.CharField(max_length=20, null=True, blank=True)

    def __str__(self):
        return str(self.id) + " ("+ str(self.title) + ")"


class Item(models.Model):
    name = models.CharField(max_length=150, null=True, unique=True)
    active = models.BooleanField(default=False)
    code = models.CharField(max_length=20, null=True, blank=True)
    item_class = models.ForeignKey(Item_class,null=True, blank=True, on_delete=models.CASCADE, related_name='item_class')
    item_type = models.ForeignKey(Item_type,null=True, blank=True, on_delete=models.CASCADE, related_name='item_type')
    alias = models.CharField(max_length=20, null=True, blank=True)
    barcode = models.CharField(max_length=50, null=True, blank=True)
    stuff_qty = models.IntegerField(null=True, blank=True)

    def __str__(self):
        return str(self.alias) + " " + str(self.name + " (" + str(self.id) + ")")


class ReceipeMaster(models.Model):
    TYPE_OPTIONS = (('FINISHED GOODS', 'FINISHED GOODS'),)
    receipe_type = models.CharField(max_length=50, choices=TYPE_OPTIONS, default=TYPE_OPTIONS[0])
    item = models.ForeignKey(Item, on_delete=models.CASCADE, related_name='receipe')
    units = models.IntegerField(default=1)
    active = models.BooleanField(default=True)

    def __str__(self):
        return str(self.item.name)

    def get_absolute_url(self):
        return reverse("item_management:recipes_show", kwargs={"pk": self.pk})


class ReceipeDetail(models.Model):
    master = models.ForeignKey(ReceipeMaster, on_delete=models.CASCADE, related_name='items')
    item_type = models.ForeignKey(Item_type, null=True, on_delete=models.PROTECT)
    item = models.ForeignKey(Item, on_delete=models.PROTECT)
    quantity = models.IntegerField()

    def __str__(self):
        return str(self.item.name) + " (" + str(self.master) + ")"

how do I get prefetch_related in the forms.inlineformset_factory

here is the code from forms.py

AddReceipeDetailFormSet = forms.inlineformset_factory(
    ReceipeMaster,
    ReceipeDetail,
    fields=( 'item_type', 'item', 'quantity'),
    extra=50,
    widgets={
        'item_type': forms.Select(attrs={'class': 'form-control'}),
        'item': forms.Select(attrs={'class': 'form-control'}),
        'quantity': forms.NumberInput(attrs={'class': 'form-control'}),
    }
)

Here is my view from views.py

def create_receipe(request):
    child_forms = AddReceipeDetailFormSet(request.POST or None)
    parent_form = ReceipeCreateForm(request.POST or None)
    context = {'parent_form': parent_form, 'child_forms': child_forms}
    if request.method == 'POST':
        if parent_form.is_valid():
            print('parent form is valid')
        else:
            print('invalid parent form', parent_form.errors)
        if child_forms.is_valid():
            print('child form is valid')
        else:
            print('invalid child form', child_forms.errors)
        print("post request is received***", request.POST)
    return render(request, 'receipes/create.html', context=context)

regards

Muhammad Sharif
  • 406
  • 6
  • 17
  • Please add your model `ReceipeMaster`, `ReceipeDetail` and also the models referred by the fields `item_type` and `item` (particularly the `__str__` method of these models and any field they may refer) to the question. – Abdul Aziz Barkat Apr 08 '21 at 13:19
  • @AbdulAzizBarkat for your feedback I have added the models for your reference, thank you – Muhammad Sharif Apr 09 '21 at 11:56
  • Does this answer your question? [Django Inline for ManyToMany generate duplicate queries](https://stackoverflow.com/questions/40665770/django-inline-for-manytomany-generate-duplicate-queries) – Abdul Aziz Barkat Apr 09 '21 at 12:38
  • Check the [answer by @isobolev](https://stackoverflow.com/a/44932400/14991864) on above linked question. With those classes he made you will write `AddReceipeDetailFormSet = forms.inlineformset_factory(ReceipeMaster, ReceipeDetail, form=CachingModelChoicesForm, formset=CachingModelChoicesFormSet, ...)` to solve your issue. (Basically the problem is that each form in the formset is making it's own query for getting the choices, the linked answer caches those choices to solve this problem) – Abdul Aziz Barkat Apr 09 '21 at 12:41

0 Answers0