Select a subset of inlineformset_factory foreign key elements in Django

I have a model with two foreign keys:

class Model1(models.Model):
  model_a = models.ForeignKey(ModelA)
  model_b = models.ForeignKey(ModelB)
  value = models.IntegerField()

Then I create a built-in formet class, for example:

an_inline_formset = inlineformset_factory(ModelA, Model1, fk_name="model_a")

and then create an instance, for example:

a_formset = an_inline_formset(request.POST, instance=model_A_object)

Once this formet is displayed in the template / page, there is a ChoiceField associated with the model_b field. The problem I am facing is that the items in the popup menu that appears include all the items found in the ModelB table. I need to select a subset of them based on some criteria from ModelB. At the same time, I need to keep the reference to the model_A_object instance when creating the inlineformset_factory instance, and therefore I cannot just use this example , Any suggestions?

+3
1

, ModelChoiceField

, . :

an_inline_formset.form.base_fields['model_b'].queryset = ModelB.objects.filter(whatever=True)

, .

+2

Source: https://habr.com/ru/post/1781384/


All Articles