开发者

Select a subset of foreign key elements in inlineformset_factory in Django

开发者 https://www.devze.com 2023-01-31 08:22 出处:网络
I have a model with two foreign keys: class Model1(models.Model): model_a = models.ForeignKey(ModelA) model_b = models.ForeignKey(ModelB)

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 an inline formset class, like so:

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

and then instantiate it, like so:

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

Once this formset gets rendered in a template/page, there is ChoiceField associated with the model_b field. The problem I'm having is that th开发者_StackOverflow社区e elements in the resulting drop down menu include all of the elements found in ModelB table. I need to select a subset of those based on some criteria from ModelB. At the same time, I need to keep the reference to the instance of model_A_object when instantiating inlineformset_factory and, therefore, I can't just use this example. Any suggestions?


What you need to do is change the ModelChoiceField's queryset

The easiest way to do this may be to monkey-patch the formset's form. You should be able to do this right after constructing the formset with:

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

Not the prettiest, but it should work.

0

精彩评论

暂无评论...
验证码 换一张
取 消