Creating modelform fields for each object in a queryset
This question is similar to this: field choices() as queryset?
For example if I have a really simple model:
class Order(models.Model):
quantity = models.FloatField()
def __unicode__(self):
return self.quantity
And the modelform is like so:
class OrderForm(models.Modelform):
class Meta:
model = Order
Then I have some queryset from another model, ie. I pull the names of all the items:
items = [item.name for item in Inventory.objects.all()]
How do I generate a quantity field for each item 开发者_StackOverflowin this list and let the verbose name of each of those fields be the name of the each item? will I need some sort of formset?
class OrderForm(models.Modelform):
class Meta:
model = Order
def __init__(self, *args, **kwargs):
super(OrderForm, self).__init__(*args, **kwargs)
self.fields['quantity'].choices = [(i.quantity, i.name) for i in Inventory.objects.all()]
精彩评论